Strings

A string is just text — a sequence of characters wrapped in quotes. Python gives strings a large set of built-in tools for building and reshaping them.

Creating strings

Single and double quotes both work and mean exactly the same thing — pick one convention and stay consistent. Triple quotes let a string span multiple lines:

python example.py
first = 'Ada'
last = "Lovelace"
bio = """Mathematician
and writer."""

f-strings

An f-string lets you drop variables straight into a string by wrapping them in curly braces, with an f right before the opening quote:

python example.py
name = "Ada"
age = 36
print(f"{name} is {age} years old.")
Output
Ada is 36 years old.

This is generally the cleanest way to build a string out of pieces — far easier to read than gluing fragments together by hand once more than one or two values are involved.

Concatenation

The + operator joins strings end to end. It's useful for small cases, though it does require both sides to already be strings:

python example.py
greeting = "Hello, " + name + "!"
print(greeting)
Output
Hello, Ada!

Useful string methods

Strings come with built-in methods for the transformations you'll reach for constantly:

python example.py
text = "Hello, World!"
print(text.upper())
print(text.lower())
print(text.replace("World", "Python"))
print(text.split(", "))
Output
HELLO, WORLD!
hello, world!
Hello, Python!
['Hello', 'World!']

None of these methods change text itself — each one returns a brand new string. .strip() (removes leading/trailing whitespace) is another one you'll use constantly, especially on text that came from user input or a file.

Slicing strings

A string is a sequence of characters, indexed starting at 0. Square brackets grab a single character; a colon inside them grabs a range, where the end index is not included:

python example.py
word = "Python"
print(word[0])
print(word[0:3])
print(word[-1])
print(word[:4])
Output
P
Pyt
n
Pyth

A negative index counts backward from the end, so -1 always means "the last character." Leaving off a side of the colon means "to the start" or "to the end."

Note: strings are immutable — word[0] = "J" raises an error. To "change" a string, you build and assign a new one, for example word = "J" + word[1:].