TExcelTAD
Home › Python › Python Strings

Python Strings

A string (str) is a sequence of characters — letters, digits, spaces, emoji, anything. Python strings are Unicode, so text in any language just works.

Creating strings

Use single or double quotes; they mean exactly the same thing. Pick whichever avoids escaping:

python · try it yourself
a = 'single quotes'
b = "double quotes"
c = "It's easy"
d = 'He said "wow"'
print(a, b, c, d, sep="\n")
single quotes
double quotes
It's easy
He said "wow"

Triple quotes (""" or ''') create a multi-line string; the line breaks are kept:

python · try it yourself
poem = """Roses are red,
Python is neat,
Indentation matters,
And so does the beat."""
print(poem)
Roses are red,
Python is neat,
Indentation matters,
And so does the beat.

Strings are sequences

Each character has a position called an index, starting at 0. Negative indexes count from the end:

Character P y t h o n
Index 0 1 2 3 4 5
Negative -6 -5 -4 -3 -2 -1
python · try it yourself
word = "Python"
print(word[0])
print(word[-1])
print(len(word))

for ch in "abc":
    print(ch.upper())
P
n
6
A
B
C

Slicing

text[start:end] extracts a substring from start up to — but not including — end. Either side can be left out, and a third value sets the step:

python · try it yourself
s = "Hello, World"
print(s[0:5])     # first five characters
print(s[7:])      # from index 7 to the end
print(s[:5])      # same as s[0:5]
print(s[-5:])     # last five characters
print(s[::2])     # every second character
print(s[::-1])    # reversed
Hello
World
Hello
World
Hlo ol
dlroW ,olleH

Strings are immutable

You can't change a character in place. Build a new string instead:

python · try it yourself
name = "jython"
try:
    name[0] = "P"
except TypeError as err:
    print("Error:", err)

name = "P" + name[1:]
print(name)
Error: 'str' object does not support item assignment
Python

Combining and repeating

Operation Example Result
Concatenate "ab" + "cd" "abcd"
Repeat "ha" * 3 "hahaha"
Membership "or" in "World" True
Not in "x" not in "abc" True
python · try it yourself
first = "Ada"
last = "Lovelace"
full = first + " " + last
print(full)
print("-" * 12)
print("Love" in full)
print("love" in full)    # checks are case-sensitive
Ada Lovelace
------------
True
False

Tip: For gluing many pieces together, " ".join(pieces) is faster and cleaner than repeated +. It's covered in String Methods.

Raw strings

Put r in front of a string to turn off escape sequences. This is handy for Windows paths and regular expressions:

python · try it yourself
print("C:\new\table")
print(r"C:\new\table")
C:
ew	able
C:\new\table

In the first line, \n became a new line and \t a tab!

Test yourself

What is "Python"[1:4]?

  1. "Pyt"
  2. "yth"
  3. "ytho"
  4. "thon"

What does "abc"[-1] return?

  1. "a"
  2. "c"
  3. An IndexError
  4. ""

Why does s[0] = "X" fail for a string s?

  1. Strings are immutable
  2. Index 0 is reserved
  3. You must use s.set(0, "X")
  4. It only fails for empty strings