Python - Strings

python logo pixel art

Strings is a sequence/string of characters or a list of chars.


Declaring Strings

To declare string, use '(single quotes) or "(double quotes).

x = 'Hi Y, how are you?'
y = "Hi X, I'm good!"

Multiline Strings

To declare a multiline string, use three consecutive quotes ''' or """.

text = '''
it's a beautiful day outside.
birds are singing, flowers are blooming...
'''

Format Strings

To declare a format string, prefix the quotes with f and use {} as placeholder.

name = 'Felipe'
age = 20
print(f"Hi! I'm {name} and I'm {age} years old.")

Raw Strings

Raw strings treat escape sequences as regular characters, to declare a raw string, prefix the quotes with r.

x = "I will break!\naaahhh"
y = r"I will not break!\nI'm ok!"

Concatenate Strings

To concate strings in python, use the + operator.

name = 'John'
surname = 'Doe'
print(name + ' ' + surname)

String Length

To obtain the length of a string use len(x).

x = "Hello, World!"
print(len(x)) # 13

String Slicing

To extract a substring from a string use the slicing syntax string[start:end].

[start:end]
[:end] # 0 to end
[start:] # start to end
x = "Hello, World!"
print(x[7:12]) # World