Combining Strings
Using the "+" Operator
The "+" operator allows concatenation of multiple strings.
str1 = "aaa"
str2 = "bbb"
result = str1 + str2
print(result)
# Output: aaabbb
Note that direct concatenation with non-string types is not allowed:
num = 100
str1 = "hello"
# print(str1 + num) # This would raise TypeError
To resolve this, convert the number to a string first:
num = 100
str1 = "hello"
result = str1 + str(num)
print(result)
# Output: hello100
Using the join() Method
The join() method combines elements of a sequence into a single string using a specified separator.
separator = "-"
sequence = ("a", "b", "c")
result = separator.join(sequence)
print(result)
# Output: a-b-c
Measuring String Length
Use the built-in len() function to determine string length:
str1 = "hello"
length = len(str1)
print(length)
# Output: 5
str2 = "你好"
length = len(str2)
print(length)
# Output: 2
In UTF-8 encoding, Chinese characters occupy three bytes each:
str1 = "你好"
print(len(str1.encode('utf-8')))
# Output: 6
Extracting Substrings
Syntax: string[start:end:step]
str1 = "hello world!"
print(str1[1]) # Output: e
print(str1[2:]) # Output: llo world!
print(str1[:4]) # Output: hell
print(str1[1:5]) # Output: ello
print(str1[-1]) # Output: !
print(str1[2:-2]) # Output: llo worl
Splitting Strings
Use the split() method to divide a string into a list.
str1 = "i am a good boy!"
parts = str1.split()
print(parts)
# Output: ['i', 'am', 'a', 'good', 'boy!']
parts = str1.split(" ", 3)
print(parts)
# Output: ['i', 'am', 'a', 'good boy!']
Searching Within Strings
count() Method
Counts occurrences of a substring within a string:
str1 = "hello world"
count = str1.count('o')
print(count)
# Output: 2
find() Method
Returns index of first occurrence or -1 if not found:
str1 = "hello world!"
index = str1.find('wo')
print(index)
# Output: 6
index() Method
Similar to find(), but raises a exception when substring is not found:
str1 = "hello world!"
try:
index = str1.index('m')
except ValueError:
print("Substring not found")
startswith() and endswith() Methods
Check whether a string starts or ends with a specific prefix or suffix:
str1 = "hello world!"
print(str1.startswith('hello')) # True
print(str1.endswith('world!')) # True
Case Conversion
lower() Method
Converts uppercase letters to lowercase:
str1 = "Hello World!"
lowercase = str1.lower()
print(lowercase)
# Output: hello world!
upper() Method
Converts lowercase letters to uppercase:
str1 = "Hello World!"
uppercase = str1.upper()
print(uppercase)
# Output: HELLO WORLD!
Removing Whitespace and Special Characters
strip() Method
Removes leading and trailing whitespace or specified characters:
str1 = " hello world! "
stripped = str1.strip()
print(stripped)
# Output: hello world!
str2 = "#hello world#@#"
stripped = str2.strip('#')
print(stripped)
# Output: hello world#@
lstrip() Method
Removes leading whitespace or specified characetrs:
str1 = " hello world! "
lstripped = str1.lstrip()
print(lstripped)
# Output: hello world!
rstrip() Method
Removes trailing whitespace or specified characters:
str1 = " hello world! "
rstripped = str1.rstrip()
print(rstripped)
# Output: hello world!
Replacing Text
The replace() method substitutes one substring with another:
original = "hello world !!! hhh"
replaced = original.replace(" ", "-")
print(replaced)
# Output: hello-world-!!!-hhh
replaced = original.replace(" ", "-", 1)
print(replaced)
# Output: hello-world !!! hhh