String in Python
Content:
In Python, a string is a sequence of characters enclosed in single quotes ('), double quotes ("), or triple quotes (''' or """).
Strings are immutable, meaning once created, they cannot be changed.
Ways to Create Strings in Python:
str1 = 'Hello, World!'
str2 = "Hello, World!"
str3 = '''
This is a
multi-line
string.
'''
str4 = str(123) # Converts the number 123 to a string
name = 'Alice'
greeting = f'Hello, {name}!' # "Hello, Alice!"
String Methods in Python:
text = 'Hello'
print(len(text)) # 5
text = 'Hello'
print(text.upper()) # "HELLO"
print(text.lower()) # "hello"
text = ' Hello, World! '
print(text.strip()) # "Hello, World!"
text = 'Hello, World!'
print(text.replace('World', 'Alice')) # "Hello, Alice!"
print(text.replace('l','b',2)) # "Hebbo, World!" # A third parameter can define the number of instances to replace
text = 'apple,banana,cherry'
print(text.split(',')) # ['apple', 'banana', 'cherry']
fruits = ['apple', 'banana', 'cherry']
print(', '.join(fruits)) # "apple, banana, cherry"
text = 'Hello, World!'
print(text.find('World')) # 7 # if not found returns -1
print(text.index('World')) # 7 # if not found throws an exception
text = 'Hello, World!'
print(text.startswith('Hello')) # True
print(text.endswith('!')) # True
fString for formatting
pi = 3.14159
print(f'{pi:.2f}') # '3.14'
print(f'{pi:10.2f}') # ' 3.14' (right-aligned in 10 chars)
print(f'{'hi':>10}') # ' hi'
print(f'{'hi':<10}') # 'hi '
print(f'{'hi':^10}') # ' hi '
print(f'{42:05d}') # '00042'
print(f'{'x'!r}') # "'x'"