iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python Strings

Strings in Python are immutable sequences of Unicode characters. You can write them with single, double, or triple quotes — pick whichever needs the least escaping.

Quotes

PYTHON
'single'
"double"
'''triple — can span
multiple lines'''
"""triple double — also multi-line"""

Indexing & slicing

PYTHON
s = 'Hello, Python!'
print(s[0])       # 'H'
print(s[-1])      # '!'
print(s[0:5])     # 'Hello'
print(s[7:])      # 'Python!'
print(s[::-1])    # reversed

Common methods

MethodReturns
len(s)Character count.
s.upper() / s.lower() / s.title()Case.
s.strip()Trim whitespace.
s.replace(a, b)Replace substring.
s.split(',')Split on delimiter.
','.join(seq)Join an iterable.
s.startswith(p) / s.endswith(p)Prefix / suffix test.
s.find(t)Index of t, or -1.

f-strings

PYTHON
name = 'Ada'
age  = 36
print(f'{name} is {age}')              # Ada is 36
print(f'{name!r} → {age:03d}')          # 'Ada' → 036
print(f'{3.14159:.2f}')                # 3.14
Tip: Strings are immutable. s.upper() returns a new string — it doesn't change s.

Example

Example
s = 'Hello, Python!'
print(len(s))
print(s.upper())
print(s.replace('Python', 'world'))
print(s[0:5])
print(f'shouted: {s.upper()!r}')
Try it Yourself »

Exercise

Use an f-string to interpolate the variable name.

'Hello, {name}!'

Test yourself

Q1. Strings in Python are…
Q2. f'{x:.2f}' formats x as…
Q3. s.upper() does what to s?

Discussion

Loading…