String¶

Strings in Python 3 are immutable sequences that use Unicode encoding.

In [6]:
se: str = ''  # Empty string
si: str = str(12345)  # Creates a string from a number
sj: str = ' '.join(['Follow', 'the', 'white', 'rabbit'])  # Joins a string from pieces using the specified separator
print(f'Joined string: {sj}')

is_contains: bool = 'rabbit' in sj  # Substring presence check
is_startswith = sj.startswith('Foll')
is_endswith = sj.endswith('bat')
print(f'is_contains = {is_contains}, is_startswith = {is_startswith}, is_endswith = {is_endswith}')

sr: str  = sj.replace('rabbit', 'sheep')  # Substring replacement. You can specify the number of replacements: sr: str  = sj.replace("rabbit", "sheep", times)
print(f'After replace: {sr}')

i1 = sr.find('rabbit')  # Returns the starting index of the first occurrence or -1. There is also rfind(), which starts searching from the end of the string
i2 = sr.index('sheep')  #  Returns the starting index of the first occurrence or raises a ValueError. There is also rindex(), which starts searching from the end of the string
print(f"Start index of 'rabbit' is {i1}, start index of 'sheep' is {i2}")

d = str.maketrans({"a" : "x", "b" : "y", "c" : "z"})
st  = "abc".translate(d)
print(f"Translate string: {st}")

sr = sj[::-1]  # Reversal using slicing with a negative step
print(f"Reverse string: {sr}")
Joined string: Follow the white rabbit
is_contains = True, is_startswith = True, is_endswith = False
After replace: Follow the white sheep
Start index of 'rabbit' is -1, start index of 'sheep' is 17
Translate string: xyz
Reverse string: tibbar etihw eht wolloF