Learn

Short lessons with real code you can edit and run on the page.

Strings in Python

Lesson 5 Python 3.14 Runs in your browser Updated
In short

A string is a sequence of characters written between quotes, and it is Python's type for text. You can read any character by position, cut out a slice, and call methods such as upper() or split(), but a string itself never changes, so every method that seems to change text gives you a new string.

Key facts

  • Single and double quotes make the same string. Pick the one that lets you use the other kind inside without a backslash.
  • Positions start at 0, and negative positions count from the end, so word[-1] is the last character.
  • A slice word[a:b] includes position a and stops before b.
  • Strings are immutable. upper(), replace() and friends return a new string and leave the original as it was.

What is a string in Python?

A string is text wrapped in quotes, from no characters at all to a whole document. Single and double quotes are interchangeable, so you can wrap the text in one kind and use the other kind inside it without a backslash.

Python
greeting = "Hello"
single = 'Hello'
quote = 'She said "hi"'
apostrophe = "It's fine"
print(greeting == single)
print(quote)
print(apostrophe)
Output
True
She said "hi"
It's fine

Three quotes in a row make a string that can span lines. The line breaks you type are part of the text.

Python
poem = """Roses are red,
violets are blue."""
print(poem)
Output
Roses are red,
violets are blue.

How do I get one character from a string?

Put the position, called an index, in square brackets. Counting starts at 0, so the first character is word[0], and negative numbers count back from the end. len() gives the number of characters.

Python
word = "Python"
print(word[0])
print(word[5])
print(word[-1])
print(len(word))
Output
P
n
n
6

How do I slice a string in Python?

Write word[start:stop]. The slice includes start and stops just before stop. Either number can be left out, so word[:2] is the first two characters and word[3:] is everything from position 3 on. A third number sets the step, how far each move goes, so 2 takes every second character and -1 reverses the string.

Python
word = "Python"
print(word[0:3])
print(word[3:])
print(word[:2])
print(word[::2])
print(word[::-1])
Output
Pyt
hon
Py
Pto
nohtyP

Because a slice stops just before its stop position, word[:3] and word[3:] split a string with nothing lost and nothing doubled.

What are the most useful string methods?

Eight methods cover most everyday text work. Each is called with a dot after the string, and each returns a new value rather than editing the string.

Useful Python string methods
MethodWhat it does
strip()Removes spaces, tabs and line breaks from both ends
upper(), lower()Returns a copy with every letter in uppercase, or in lowercase
replace(old, new)Swaps every occurrence of one piece of text for another
split(sep)Cuts the string into a list at each separator
join(list)Glues a list of strings together, putting the string you call it on between the items
find(text)Returns the position of the first match, or -1 when there is none
count(text)Counts how many times a piece of text appears, without counting overlapping matches
Python
text = "  Hello, World!"
print(text.strip())
print(text.upper())
print(text.lower())
print(text.replace("World", "Python"))
print(text.strip().split(", "))
print("-".join(["a", "b", "c"]))
print(text.find("World"))
print(text.count("l"))
Output
Hello, World!
  HELLO, WORLD!
  hello, world!
  Hello, Python!
['Hello', 'World!']
a-b-c
9
3

Methods chain. text.strip().split(", ") strips first, then splits what is left into a list.

Can I change a string in Python?

No. Strings are immutable, so a method such as capitalize(), which returns a copy with the first character in uppercase and the rest in lowercase, leaves the original alone. To get a changed version, build a new string from pieces of the old one and assign it to a name. Trying to assign into a position raises a TypeError.

Python
word = "python"
print(word.capitalize())
print(word)
new_word = "J" + word[1:]
print(new_word)
Output
Python
python
Jython
Python
word = "python"
word[0] = "J"
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    word[0] = "J"
    ~~~~^^^
TypeError: 'str' object does not support item assignment

How do I join and repeat strings?

+ joins two strings, * repeats one, in checks whether one string contains another, and len() counts characters. To mix text with numbers, use an f-string, which the next lesson covers.

Python
first = "Ada"
last = "Lovelace"
print(first + " " + last)
print("ha" * 3)
print("Love" in last)
print(len(first + last))
Output
Ada Lovelace
hahaha
True
11

What is an r-string in Python?

A raw string, written with an r before the quote, keeps backslashes as they are. In a normal string a backslash starts an escape, so \n is a line break, \t a tab and \" a quote that does not end the string, and a real backslash has to be doubled.

Raw strings save that doubling in file paths and in regular expressions, patterns for searching text, but a raw string still can't end with a single backslash, so r"C:\Users\" is a SyntaxError.

Python
print("Line one\nLine two")
print("Tab\there")
print("C:\\Users\\Ada")
print(r"C:\Users\Ada")
Output
Line one
Line two
Tab	here
C:\Users\Ada
C:\Users\Ada

Common mistakes with strings in Python

Each of these four mistakes with Python strings has a quick fix once you know the cause.

  • IndexError: string index out of range. The last position is len(word) - 1, so "Python"[6] fails. Use word[-1] for the last character.
  • TypeError: 'str' object does not support item assignment. You tried word[0] = "J". Build a new string instead.
  • Calling a method and ignoring the result. word.upper() on its own line changes nothing. Assign the result, as in word = word.upper().
  • Adding a number to a string. "5" + 5 raises a TypeError. To join them, convert the number with str() or use an f-string. To do math, convert the text with int().
Python
word = "Python"
print(word[6])
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(word[6])
          ~~~~^^^
IndexError: string index out of range

Exercise

Complete the two print lines so the program prints the word with its first letter capitalized, Python, and then the original lowercase word reversed, nohtyp. A string method does the first line and a slice does the second. Leave the variable word as it is.

Python
word = "python"

print()
print()
Output
Show the solution
word = "python"

print(word.capitalize())
print(word[::-1])

Quiz

This quiz has 5 questions. Pick an answer to see why it is right or wrong.

  1. 1What does this program print?

    word = "Python"
    print(word[1:4])
  2. 2What does this program print?

    word = "hello"
    word.upper()
    print(word)
  3. 3Which expression gives the last character of a string s?

  4. 4What does this program print?

    print(r"a\nb")
  5. 5What does "-".join(["1", "2", "3"]) return?

Frequently asked questions

What is a string in Python?
A string is a sequence of characters between quotes, the type Python uses for text. Its type is str, and it can hold anything from no characters at all to a whole file.
Is str() a string method?
No. str is the string type, and calling it like a function, as in str(42), converts a value to a string. String methods are called on a string with a dot, such as "abc".upper().
What is an r-string in Python?
A raw string, written r"..." or r'...', treats backslashes as ordinary characters instead of escape codes. It is the usual way to write Windows paths and regular expressions, which are patterns for searching text, but it still can't end with a single backslash.
How do I reverse a string in Python?
Slice it with a step of -1, as in "Python"[::-1], which gives "nohtyP". There is no reverse() method on strings.
Are Python strings mutable?
No. A string never changes after it is created. Every method that looks like it edits a string returns a new one, so assign the result if you want to keep it.
Should I use single or double quotes in Python?
Either. They create identical strings. Pick the kind that isn't in the text, so "It's" and 'She said "hi"' need no backslashes.