Learn Python / Strings

Strings

A string is a piece of text: a name, a sentence, a password, a whole file. Strings are one of the types you'll use most. In this lesson you'll learn how to build strings and pick out parts of them. The next lesson covers the many built-in tools for changing them.

Creating strings

Put text inside single or double quotes. For text that spans several lines, use triple quotes:

first = "Hello"
second = 'World'
poem = """Roses are red,
Violets are blue,
Python is fun,
And so are you."""

print(first, second)
print(poem)
Output

Joining and repeating

+ joins strings end to end, and * repeats a string:

first_name = "Ada"
last_name = "Lovelace"

full_name = first_name + " " + last_name
print(full_name)

print("ha" * 3)
print("-" * 20)
Output

Notice the " " in the middle: + doesn't add spaces for you.

Counting characters with len()

len() tells you how many characters a string has. Spaces and punctuation count too:

print(len("Python"))
print(len("Hello, World!"))
print(len(""))   # an empty string has length 0
Output

Indexing: getting one character

Each character in a string has a numbered position called an index. Python starts counting at 0, not 1, so the first character is at index 0. Negative indexes count backwards from the end:

 P   y   t   h   o   n
 0   1   2   3   4   5
-6  -5  -4  -3  -2  -1

Put the index in square brackets after the string:

Predict first: using the diagram above, what will each line print?

word = "Python"

print(word[0])
print(word[3])
print(word[-1])
print(word[-2])
Output

word[0] is always the first character and word[-1] is always the last, however long the string is.

Asking for a position that doesn't exist raises an IndexError:

word = "Python"
print(word[10])
Output

Slicing: getting part of a string

A slice gives you a piece of a string. word[start:end] takes the characters from start up to, but not including, end:

word = "Python"

print(word[0:2])   # positions 0 and 1
print(word[2:5])   # positions 2, 3 and 4
Output

Leave out start to begin at the start, or end to go all the way to the end:

word = "Python"

print(word[:3])    # the first 3 characters
print(word[3:])    # everything from position 3 on
print(word[-3:])   # the last 3 characters
Output

Tip: word[:3] means "the first 3 characters" and word[-3:] means "the last 3 characters". These two patterns cover most everyday slicing.

Reversing a string

One more pattern is worth memorising: word[::-1] gives the string reversed.

print("Python"[::-1])
print("stressed"[::-1])
Output
Going deeper: How [::-1] works: the step optional

A slice can take a third number, the step, which says how far to jump each time: word[start:end:step]. A step of 2 takes every second character, and a negative step walks backwards, so [::-1] means "the whole string, backwards one character at a time".

word = "Python"

print(word[::2])     # every second character
print(word[1::2])    # every second character, starting at position 1
print(word[::-1])    # backwards
print(word[::-2])    # backwards, every second character
Output

Strings can't be changed

Once a string is created, you can't change a single character inside it:

word = "Python"
word[0] = "J"
Output

Instead, build a new string from the pieces you want:

word = "Python"
new_word = "J" + word[1:]
print(new_word)
Output

Programmers say strings are immutable, which just means "can't be changed in place".

Special characters

A backslash \ inside a string starts a special character. You met \n (new line) in the first lesson. Here are the common ones:

Write To get
\n a new line
\t a tab (a wide space)
\" a double quote inside double quotes
\' a single quote inside single quotes
\\ a backslash
print("Line one\nLine two")
print("Name:\tAda")
print("She said \"hi\"")
print("C:\\Users\\Ada")
Output
Going deeper: Raw strings: when backslashes get in the way optional

Windows file paths are full of backslashes, and some of them accidentally form special characters. Here \n in \new becomes a new line:

print("C:\new_folder\notes.txt")
Output

Put an r before the opening quote to make a raw string. In a raw string, a backslash is just a backslash:

print(r"C:\new_folder\notes.txt")
Output

Raw strings are also common in regular expressions, a mini-language for searching text that uses lots of backslashes.

Exercises

Exercise 1: Initials

Print the initials of the name below, followed by full stops: A.L.

first_name = "Ada"
last_name = "Lovelace"
Output

Exercise 2: The middle part

Use a slice to print just yth from the word.

word = "Python"
Output

Exercise 3: Underline a title

Print the title, and underneath it a line of = signs exactly as long as the title:

Shopping list
=============
title = "Shopping list"
Output

Exercise 4: Palindrome check

A palindrome reads the same forwards and backwards. Print True if word is a palindrome.

word = "racecar"
Output

String operations at a glance

A quick reference for later. Each example starts from s = "Python". Results are shown with quotes, so you can see exactly where each string starts and ends.

Operation What it does Example Result
s[i] The character at position i (counting from 0) s[0] 'P'
s[-i] Counts from the end: -1 is the last character s[-1] 'n'
s[start:end] A slice, from start up to (not including) end s[1:4] 'yth'
s[:n] The first n characters s[:2] 'Py'
s[-n:] The last n characters s[-3:] 'hon'
s[::-1] The string reversed s[::-1] 'nohtyP'
s + other Joins two strings s + "!" 'Python!'
s * n Repeats the string n times s * 2 'PythonPython'
len(s) Number of characters len(s) 6
x in s Does x appear inside s? "th" in s True
str(x) Turns a value into a string str(42) '42'

Strings also have dozens of built-in methods, such as upper() and replace(). They're the topic of the next lesson, String Methods.

Summary

  • Strings are text in quotes. Use triple quotes for text over several lines.
  • + joins strings, * repeats them, and len() counts characters.
  • Indexes start at 0: s[0] is the first character and s[-1] the last.
  • s[start:end] slices out a piece. The end is not included.
  • s[:3] gives the first 3 characters, s[-3:] the last 3, and s[::-1] reverses.
  • Strings can't be changed in place. Build a new string instead.
  • \n starts a new line, and \t adds a tab.