After this lesson you can write text in Python with confidence: choose the right quotes, put a quote or a new line inside a string, join pieces together, and measure how long a string is.
What a string is
A string is a piece of text. Python stores it as a sequence of characters: letters, digits, spaces, punctuation and symbols. You write one by putting characters between quotes. Single and double quotes mean exactly the same thing, so pick one style and stay consistent.
shop = "Green Leaf Books"
slogan = 'Read something new'
print(shop)
print(slogan)
print(type(shop))Green Leaf Books
Read something new
<class 'str'>The class name is str. An empty string, written "", is perfectly valid and has no characters at all.
Quotes inside a string
If the text contains an apostrophe, wrap it in double quotes. If it contains double quotes, wrap it in single quotes. Python only ends the string when it meets the same kind of quote that began it.
print("It's open until six")
print('She said "welcome" at the door')It's open until six
She said "welcome" at the doorWhen you need both kinds, or you want to be explicit, use a backslash escape, as the next section shows.
Escape sequences
A backslash tells Python that the next character is special. The ones you will use most are \n for a new line, \t for a tab, \\ for one real backslash and \' or \" for a quote character.
print("Line one\nLine two")
print("Item\tPrice")
print('It\'s fine')
print("C:\\shop\\prices")Line one
Line two
Item Price
It's fine
C:\shop\pricesThe backslash is not part of the output. It is an instruction to Python. If you are writing something full of backslashes, such as a Windows folder path, a raw string saves effort. Put r straight before the opening quote and Python leaves every backslash exactly as typed.
print(r"C:\shop\prices")
print(r"no \n new line here")C:\shop\prices
no \n new line hereStrings over several lines
Triple quotes, using either """ or ''', let a string run across many lines. Every new line and space you type is kept.
receipt = """Green Leaf Books
Thank you for visiting
Come again soon"""
print(receipt)Green Leaf Books
Thank you for visiting
Come again soonTriple-quoted strings are also the usual way to write the longer explanations that go at the top of functions, which you will see later in the course.
Joining and repeating
The + operator joins two strings into a longer one. This is called concatenation. The * operator repeats a string a whole number of times.
first = "Maya"
last = "Rao"
full = first + " " + last
print(full)
print("-" * 20)
print("ha" * 3)Maya Rao
--------------------
hahahaJoining does not add spaces for you, so include them yourself. Repeating is a quick way to draw a divider line in text output.
Length and membership
The built-in len() returns the number of characters. The in operator asks whether one piece of text appears anywhere inside another, and answers True or False. Both count spaces and are case sensitive.
title = "Green Leaf Books"
print(len(title))
print("Leaf" in title)
print("leaf" in title)
print("Moon" not in title)16
True
False
TrueThe third line is False because lowercase leaf is not the same text as Leaf. Later lessons show how to change case before comparing.
Strings never change
A string is immutable, which means you cannot alter it once it exists. Every operation that seems to change a string actually builds a new one. Trying to change a character in place fails:
word = "cat"
word[0] = "b"TypeError: 'str' object does not support item assignmentThe fix is to build a replacement. Here + makes a brand new string and the name word is pointed at it.
word = "cat"
word = "b" + word[1:]
print(word)batYou will learn what word[1:] means in the lesson on slicing. The key idea for now is that the old string was not edited. A new one was made.
Text and numbers do not mix
Python refuses to join a string and a number, because it cannot tell whether you want arithmetic or text.
print("Items in basket: " + 3)TypeError: can only concatenate str (not "int") to strWrap the number in str() to turn it into text, or use the formatting tools covered later in the course.
print("Items in basket: " + str(3))Items in basket: 3Strings are everywhere
Almost every real program handles text: names in a signup form, the title of a book, an error message, a line read from a file or a web address. That is why it pays to be comfortable with the basics early. Remember the three facts that explain most of the behaviour you will meet. A string is a sequence of characters, so it has a length and an order. A string is immutable, so operations produce new strings. And a string is a different type from a number, so the two never mix without a conversion. The lessons that follow build on exactly these facts, adding methods for changing text, positions for picking pieces out, and formatting for presenting it neatly.
Common mistakes
- Forgetting to close a quote. A missing closing quote gives a syntax error, often reported on a later line than the real fault.
- Mixing quote styles. A string that starts with a single quote must end with a single quote.
- Expecting
+to add spaces."Hello" + "there"givesHellothere. - Writing a Windows path with single backslashes.
"C:\new"contains a new line because of\n. Use a raw string or double the backslashes. - Trying to change one character with an index. Build a new string instead.
A video version of this topic is in the video course at /learn/python/.
Exercise
Build a name tag for a library member. Store the member name Isha Menon and the library name City Library in two variables. Print a line of 24 equals signs, then the member name, then the library name on its own line (use \n once, in a single print call), then another line of 24 equals signs. Finally print how many characters the member name has.
Show a possible answer
member = "Isha Menon"
library = "City Library"
print("=" * 24)
print(member + "\n" + library)
print("=" * 24)
print(len(member))========================
Isha Menon
City Library
========================
10Key points
- A string is a sequence of characters written inside single, double or triple quotes.
- A backslash starts an escape sequence such as \n for a new line and \t for a tab. Raw strings, written r"...", leave backslashes alone.
- + joins strings, * repeats them, len() counts characters and in tests whether one piece of text appears inside another.
- Strings are immutable. Every operation builds a new string and leaves the original unchanged.
- You cannot add a number to a string directly. Convert the number first.