Python Strings
1Python Strings: overview
A string is a sequence of characters — text — written inside quotes, which you can index, slice, combine and transform with built-in methods.
Before this lesson: Python Variables, Python Data Types
2Python Strings: diagram
3Python Strings: explained step by step
A string (str) is a piece of text: a sequence of characters inside quotes. Single and double quotes work the same way, so choose whichever lets you include the other one inside — "It's here" or 'She said "hi"'. Triple quotes ("""...""") let a string run over several lines.
Indexing and slicing
Because a string is a sequence, every character has a numbered position. Counting starts at 0 on the left, and negative indexes count from the right, with -1 as the last character.
A slice text[start:stop] takes the characters from start up to — but not including — stop. Leave out a number to mean "from the beginning" or "to the end", and add a third number to set a step.
word = "Python"
print(word[0], word[-1])
print(word[1:4])
print(word[:2], word[2:])
print(word[::-1])
print(len(word))Strings are immutable
Once a string exists, it can't be changed: word[0] = "J" raises a TypeError. Instead, you build a new string from pieces — "J" + word[1:] gives "Jython".
This is also why string methods never change the original. They return a new string, and you have to store that result if you want to keep it. name.upper() on a line by itself achieves nothing; name = name.upper() does.
Useful string methods
A method is a function that belongs to a value, called with a dot: text.upper(). These are the ones you'll reach for most often:
upper(),lower(),title()— change the letter casestrip()— remove spaces (and newlines) from both endsreplace(old, new)— swap every occurrence of one piece of text for anothersplit(sep)— break the text into a list of parts; with no argument it splits on any whitespacesep.join(parts)— the reverse of split: glue a list of strings together withsepbetween themstartswith(),endswith(),find(),count()— search the text
raw = " learn python today "
clean = raw.strip()
print(clean.upper())
print(clean.replace("today", "now"))
words = clean.split()
print(words)
print("-".join(words))
print("python" in clean)The last line uses in, which checks whether one string appears inside another.
Building text with f-strings
Gluing pieces together with + quickly gets messy, and every number needs str() around it. An f-string — a string with f just before the opening quote — lets you put any variable or expression inside {}, and Python fills in its value. A format code after a colon controls the look: {price:.2f} always shows two decimal places.
name = "Asha"
items = 3
total = 7.5
print(f"{name} bought {items} items for ${total:.2f}")
print(f"Next week {name} wants {items * 2} items")Special characters
A backslash inside a string starts an escape sequence: \n is a new line, \t is a tab, and \" puts a double quote inside a double-quoted string.
Quick reference: Python Strings
- Python String Cheat Sheet: Methods and Formatting — Python strings are immutable text: use slicing to cut them, methods such as `upper()`, `strip()`, `split()` a…
- Python Regex Cheat Sheet (re Module Quick Reference) — Python regular expressions live in the `re` module: write the pattern as a raw string, then use `re.search()`…
- Python str() vs repr(): What Is the Difference? — `str()` returns a **readable** version of an object meant for users, while `repr()` returns an **unambiguous*…
- How to Reverse a String in Python — Use slicing: `text[::-1]` returns a new string with the characters in reverse order. `"".join(reversed(text))…
- How to Check if a String Contains a Substring in Python — Use the `in` operator: `"cat" in "concatenate"` returns `True` if the substring appears anywhere in the strin…
- How to Remove Whitespace from a String in Python — Use `text.strip()` to remove whitespace from both ends, or `"".join(text.split())` to remove it everywhere, i…
- How to Convert a String to a List in Python — Use `text.split()` to get a list of words, `text.split(",")` to split on a separator, or `list(text)` to get …
- How to Split a String into Words in Python — Call `text.split()` with no arguments: it splits on any whitespace and returns a list of words, such as `"to …
4Python Strings: syntax
text[i] # one character (0 = first, -1 = last)
text[start:stop] # slice -> new string (stop not included)
len(text) # number of characters
text.upper() text.lower() text.strip()
text.replace(old, new) # every old -> new
text.split(sep) # -> list of strings
sep.join(parts) # list of strings -> one string
f"Hi {name}, you owe {price:.2f}"
5Python Strings: run the example
Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.
raw_name = " ada LOVELACE "
name = raw_name.strip().title()
print(name)
first, last = name.split()
initials = first[0] + last[0]
print("Initials:", initials)
print("Last name length:", len(last))
email = name.lower().replace(" ", ".") + "@example.com"
print(email)
print(email.endswith(".com"))
username = last[:4].lower() + str(len(first))
print(f"Welcome, {first}! Your username is {username}.")
print("Original: [" + raw_name + "]")Expected outputAda Lovelace
Initials: AL
Last name length: 8
ada.lovelace@example.com
True
Welcome, Ada! Your username is love3.
Original: [ ada LOVELACE ]
7Python Strings: how the example works
Hover or tap a step to highlight its lines in the example above.
- Line 1The raw text has extra spaces and odd capitals — the kind of thing people type into forms.
- Line 2-3Methods can be chained:
strip()returns a new string without the outer spaces, thentitle()capitalises the first letter of each word. - Line 5
split()with no argument breaks the text at the space and gives two strings, which are unpacked intofirstandlast. - Line 6-7
first[0]andlast[0]are the first characters of each name;+joins them into"AL". - Line 8
len()counts the characters in"Lovelace": 8. - Line 10-11
lower()gives"ada lovelace",replace()swaps the space for a dot, and+adds the domain on the end. - Line 12
endswith()answers a yes/no question, so it returns a bool:True. - Line 14
last[:4]slices the first four characters,"Love".len(first)is a number, sostr()converts it before joining:"love3". - Line 15In the f-string, each
{...}is replaced by the value of the variable inside it. - Line 16
raw_namestill has its spaces and capitals. Every method returned a new string and left the original untouched, because strings are immutable.
8Python Strings: common mistakes
Trying to change one character
✗ Wrong
word = "cat"
word[0] = "b"✓ Right
word = "cat"
word = "b" + word[1:]
print(word)Strings are immutable, so you can't replace a character in place. Build a new string from pieces instead and assign it to the variable.
Calling a method without saving the result
✗ Wrong
city = " paris "
city.strip()
city.title()
print("[" + city + "]")✓ Right
city = " paris "
city = city.strip().title()
print("[" + city + "]")strip() and title() return new strings; they don't change city. Assign the result back to the variable.
Forgetting the f in an f-string
✗ Wrong
name = "Leo"
print("Hi {name}!")✓ Right
name = "Leo"
print(f"Hi {name}!")Without the f before the opening quote, the braces are just ordinary characters. Add f so Python fills in the value.
9Python Strings: exercises
Write your answer, then press Check. The checks run in your browser.
1. Clean up typed text
Write code Easy ✓ Completedraw holds messy text typed by a user. Create a variable clean with the same text without the spaces at both ends and in lowercase, then print it. Leave raw itself unchanged.
raw = " HeLLo WoRLD "
# create clean hereraw = " HeLLo WoRLD "
clean = raw.strip().lower()
print(clean)
2. Predict the slices
Predict the output Medium ✓ CompletedRead the code and type exactly what it prints. Sketch the indexes of "notebook" on paper if it helps.
s = "notebook"
print(s[0], s[-1])
print(s[4:])
print(s[:4].upper())
print(s.replace("o", "0"))
print(len(s[1:3]))n k
book
NOTE
n0teb00k
2
2 more exercises → 4 more examples
Questions learners ask
Should I use single or double quotes for Python strings?
They behave exactly the same. Pick one style and stick with it, and switch to the other when the text itself contains a quote, as in "It's" or 'She said "hi"'.
Why doesn't upper() or replace() change my string?
Strings are immutable: they can never be changed in place. Methods such as upper(), strip() and replace() return a new string, so assign the result, for example text = text.upper().
How do I reverse a string in Python?
Use a slice with a step of -1: text[::-1]. It walks the string from the end to the start and returns a new, reversed string.
Further reading
10Next lesson
Up nextPython String MethodsA string method is a built-in function called on text with a dot, such as text.strip() or text.split(), that returns a …Related:
Python Input and OutputPython ListsPython Regular Expressions (regex)
← Python Operators · All Python Basics lessons · Practise in the IDE