Python/Data type

Python data type - String

kimble2 2024. 7. 30. 21:55
반응형

In Python, strings are a fundamental data type used to represent sequences of characters. They are commonly used to handle and manipulate textual data. A string in Python is enclosed within either single quotes ('...') or double quotes ("..."). Multi-line strings can be enclosed within triple quotes ('''...''' or """...""").

 

Characteristics of Strings

  1. Immutable: Strings in Python are immutable, meaning once they are created, their content cannot be changed. Any operation that seems to modify a string actually creates a new string.
  2. Indexed: Strings are indexed collections, which means you can access individual characters using their index, starting from 0.
  3. Slicing: Subsets of strings can be obtained using slicing.

Creating Strings

single_quote_str = 'Hello, World!'
double_quote_str = "Hello, World!"
multi_line_str = '''This is a
multi-line string.'''

String Operations

1.Concatenation:

  • Combine two or more strings using the + operator.
greeting = "Hello" + ", " + "World!"

2.Repetition:

  • Repeat a string multiple times using the * operator.
repeated = "Ha" * 3  # "HaHaHa"

3,Indexing:

  • Access specific characters using their index.
first_char = greeting[0]  # 'H'
last_char = greeting[-1]  # '!'

4.Slicing:

  • Extract a substring using the slicing syntax [start:stop:step].
substring = greeting[7:12]  # 'World'

5.Length:

  • Determine the number of characters in a string using the len() function.
length = len(greeting)  # 13

 

6.String Methods:

  • Python provides a rich set of built-in methods for strings.
# Conversion to uppercase and lowercase
upper_case = greeting.upper()  # "HELLO, WORLD!"
lower_case = greeting.lower()  # "hello, world!"

# Checking for substring presence
has_hello = "Hello" in greeting  # True

# Stripping whitespace
stripped = "  Hello ".strip()  # "Hello"

# Splitting and joining
words = greeting.split(", ")  # ['Hello', 'World!']
joined = ", ".join(words)     # "Hello, World!"

# Finding substrings
position = greeting.find("World")  # 7

# Replacing substrings
new_greeting = greeting.replace("World", "Python")  # "Hello, Python!"

 

7.Formatting Strings:

  • Format strings using different methods to include variables and expressions within them.
  • Old-style formatting (% operator):
name = "Alice"
age = 30
formatted_str = "Name: %s, Age: %d" % (name, age)
  • str.format() method:
formatted_str = "Name: {}, Age: {}".format(name, age)
  • f-strings (formatted string literals):
formatted_str = f"Name: {name}, Age: {age}"

 

Escaping Characters:

  • Use the backslash (\) to escape special characters within strings.
escaped_str = "He said, \"Hello!\""
newline_str = "This is the first line.\nThis is the second line."

 

String Encoding and Decoding

  • Strings in Python are Unicode by default. However, they can be encoded to bytes using specific encodings like UTF-8.
# Encoding
byte_str = "Hello".encode('utf-8')  # b'Hello'

# Decoding
original_str = byte_str.decode('utf-8')  # "Hello"

 

Strings in Python are versatile and widely used. They support a vast array of operations and methods, making them powerful tools for text manipulation and processing. Whether you're dealing with simple text or complex string manipulation, Python's string capabilities are extensive and robust.

반응형

'Python > Data type' 카테고리의 다른 글

Python Data type - set  (0) 2024.08.03
Python Data type - dictionary  (0) 2024.08.03
Python Data type - tuple  (0) 2024.08.03
Python Data type - list  (0) 2024.07.30
Python data types - number  (0) 2024.07.30