Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 149 Β· Data Types

Strings

Learn Python strings - single, double and triple quotes, escape sequences, raw strings, indexing characters, immutability, and joining and repeating text.

Text is everywhere in programs: names, messages, file contents, web pages, commands. In Python, a piece of text is a string, of type str. A string is a sequence of characters, and it can hold anything from a single letter to a whole book, in any language, emoji included.

This lesson covers how to write strings, how to include special characters such as quotes and newlines, how to reach individual characters by position, and why you can't change a string in place. The next two lessons build on this with String Methods and String Formatting.

Writing strings

You create a string by wrapping text in quotes. Single quotes and double quotes mean exactly the same thing:

Python Single and double quotes

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Having both kinds is convenient when the text itself contains a quote: use the other kind on the outside.

Python
print("It's raining.")            # apostrophe inside double quotes
print('She said "hi" and left.')  # double quotes inside single quotes

Pick one style for your project and use the other only when needed. Many Python projects prefer double quotes, and formatting tools such as Black use them by default.

Escape sequences

Some characters are hard to type inside a string: a newline, a tab, or the same quote you used to open the string. A backslash \ starts an escape sequence, a short code that stands for one special character:

Escape Meaning
\n newline
\t tab
\\ a single backslash
\' and \" a quote that doesn't end the string
\u00e9 the Unicode character with that code (Γ©)
\N{SNOWMAN} the Unicode character with that name (β˜ƒ)
Python Escape sequences

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

len("a\nb") is 3, not 4: an escape sequence is written with two or more characters but produces just one character in the string.

Watch out for Windows paths. In "C:\new\table.txt", Python reads \n as a newline and \t as a tab. Use forward slashes ("C:/new/table.txt", which Windows accepts), double the backslashes, or use a raw string.

Raw strings

Put an r in front of the opening quote and Python treats backslashes as ordinary characters. That's a raw string:

Python Raw strings

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Raw strings are especially useful for Windows paths and for regular expressions, which use lots of backslashes. One quirk: a raw string can't end with a single backslash, because \" still prevents the quote from closing the string.

Multi-line strings

Triple quotes, """ or ''', create a string that can span several lines. The line breaks you type become part of the string:

Python Triple-quoted strings

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Everything between the triple quotes is kept, including indentation. Inside indented code, that can add unwanted spaces; textwrap.dedent() from the standard library removes the common leading indentation.

Triple-quoted strings are also used for docstrings, the documentation at the top of functions, classes and modules.

Joining literals across lines

Two string literals placed next to each other are joined automatically. Inside parentheses, this lets you split a long string without any + and without adding newlines:

Python
warning = (
    "Your session will expire in 5 minutes. "
    "Save your work to avoid losing changes."
)

Indexing: getting single characters

A string is an ordered sequence of characters, and each character has a position called its index. Indexes start at 0. Negative indexes count from the end, so -1 is the last character:

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

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line fails with an IndexError because a 6-character string has indexes 0 to 5. Negative indexes are the clean way to reach the end without computing the length.

You can also take a range of characters, called a slice, with language[0:3] (giving "Pyt"). Slicing works on strings, lists and tuples alike and has its own lesson, Slicing.

Python has no separate "character" type: language[0] is simply a string of length 1.

Strings are immutable

Once a string exists, it can't be changed. Assigning to an index is an error:

Python Immutability

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

word[1:] is a slice meaning "from index 1 to the end". The name word now refers to a brand-new string; the old "jello" is discarded. Every string method, such as .upper() or .replace(), works this way: it returns a new string and leaves the original alone. Forgetting this is a classic beginner bug:

Python
name = "ada"
name.upper()         # result is thrown away
print(name)          # still 'ada'

name = name.upper()  # keep the result
print(name)          # 'ADA'

Combining and repeating strings

+ joins (concatenates) strings and * repeats them. in checks whether one string appears inside another:

Python Joining, repeating, searching

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

+ only works between two strings. To include a number, convert it with str(), or better, use an f-string: f"{first} is {age} years old".

Tip: Building a long string by adding pieces in a loop works, but each + creates a new string. When you have many pieces, collect them in a list and join them once with "".join(pieces). You'll see join() in String Methods.

Comparing strings

== checks whether two strings contain exactly the same characters. < and > compare alphabetically, character by character, using each character's Unicode code point:

Python
print("apple" == "apple")   # True
print("apple" < "banana")   # True
print("Zebra" < "apple")    # True! Uppercase letters come before lowercase
print(ord("Z"), ord("a"))   # 90 97

ord() gives a character's code point and chr() turns a code point back into a character. For case-insensitive comparison, compare lowercased versions: a.lower() == b.lower().

Unicode: every language welcome

Python 3 strings are Unicode, so they can hold any writing system and emoji. len() counts characters (code points), not bytes:

Python
city = "東京"
print(len(city))                  # 2 characters
print(len(city.encode("utf-8")))  # 6 bytes when stored as UTF-8

Converting text to bytes for files or networks is called encoding; UTF-8 is the standard choice. You'll see encodings again in Reading and Writing Files.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What does "Python"[-1] evaluate to?

    Negative indexes count from the end, and -1 is the last character.
  2. 2. What is len("a\tb")?

    The escape sequence \t is written with two characters but produces a single tab character, so the string is a, tab, b.
  3. 3. After s = "cat" and s.upper(), what is s?

    Strings are immutable. upper() returns a new string, which was thrown away here. Write s = s.upper() to keep it.
  4. 4. Which string prints a Windows path with its backslashes intact?

    In a raw string (r prefix), backslashes are ordinary characters. In a normal string, \t and \n would become a tab and a newline.
  5. 5. What does "ab" * 3 + "!" produce?

    * repeats the string first (multiplication binds tighter than addition), then + adds the exclamation mark.

Summary

  • Strings (str) are written with single or double quotes; use one kind outside when the text contains the other.
  • Escape sequences like \n, \t, \\, \" and \u00e9 stand for special characters.
  • Raw strings (r"...") keep backslashes as-is: ideal for Windows paths and regular expressions.
  • Triple quotes create multi-line strings and docstrings.
  • Indexes start at 0; negative indexes count from the end. Out-of-range indexes raise IndexError.
  • Strings are immutable: methods return new strings, so assign the result.
  • + joins, * repeats, in searches, and comparisons are case-sensitive.

Next: String Methods, the built-in toolkit for changing case, trimming, splitting, searching and replacing text.