Python Strings
Beginner Python Basics

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.

GoalBy the end you can index and slice a string, clean and transform text with methods, build messages with f-strings, and explain why string methods return new strings.

Before this lesson: Python Variables, Python Data Types

2Python Strings: diagram

Python Stringsword"P"[0][-6]"y"[1][-5]"t"[2][-4]"h"[3][-3]"o"[4][-2]"n"[5][-1]word[1:4] -> "yth", word[0] -> "P", word[-1] -> "n"
Each character of "Python" sits in a numbered box: indexes run 0 to 5 from the left and -6 to -1 from the right. The highlighted boxes are the slice word[1:4] — the stop index 4 is not included.

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.

Python
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 case
  • strip() — remove spaces (and newlines) from both ends
  • replace(old, new) — swap every occurrence of one piece of text for another
  • split(sep) — break the text into a list of parts; with no argument it splits on any whitespace
  • sep.join(parts) — the reverse of split: glue a list of strings together with sep between them
  • startswith(), endswith(), find(), count() — search the text
Python
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.

Python
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

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.

Interactive example
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.

  1. Line 1The raw text has extra spaces and odd capitals — the kind of thing people type into forms.
  2. Line 2-3Methods can be chained: strip() returns a new string without the outer spaces, then title() capitalises the first letter of each word.
  3. Line 5split() with no argument breaks the text at the space and gives two strings, which are unpacked into first and last.
  4. Line 6-7first[0] and last[0] are the first characters of each name; + joins them into "AL".
  5. Line 8len() counts the characters in "Lovelace": 8.
  6. Line 10-11lower() gives "ada lovelace", replace() swaps the space for a dot, and + adds the domain on the end.
  7. Line 12endswith() answers a yes/no question, so it returns a bool: True.
  8. Line 14last[:4] slices the first four characters, "Love". len(first) is a number, so str() converts it before joining: "love3".
  9. Line 15In the f-string, each {...} is replaced by the value of the variable inside it.
  10. Line 16raw_name still 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"
TypeError: 'str' object does not support item assignment

✓ 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 + "]")
No error, but it prints [ paris ] — the text is unchanged

✓ 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}!")
No error, but it prints Hi {name}! literally

✓ 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

raw 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.

Your code
raw = "   HeLLo WoRLD   "

# create clean here

2. Predict the slices

Predict the output Medium

Read the code and type exactly what it prints. Sketch the indexes of "notebook" on paper if it helps.

Read this code
s = "notebook"
print(s[0], s[-1])
print(s[4:])
print(s[:4].upper())
print(s.replace("o", "0"))
print(len(s[1:3]))

2 more exercises → 4 more examples

Finished this lesson?
Progress is saved in this browser — create a free account to keep it across devices.

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