Strings

Topic 3 of 5 in Values and variables6 min readBeginnerFree course

Overview

Text is everywhere in programs: names, messages, file contents, web pages. In Python, text is a string (str) — a sequence of characters. This lesson covers creating strings, putting them together, and taking them apart.

Creating strings

Python
greeting = "Hello"
reply = 'Hi there'
quote = "It's raining"              # use double quotes when the text has an apostrophe
speech = 'She said "yes"'           # and single quotes when it has double quotes
poem = """Roses are red,
violets are blue."""                # triple quotes for text over several lines

Single and double quotes are equivalent; pick one style (most projects use double) and switch only when the text contains that quote.

Escape sequences

A backslash starts a special character:

Escape Meaning
\n new line
\t tab
\" / \' a quote inside quotes of the same kind
\\ a backslash itself
Python
print("Line one\nLine two")
print("Path: C:\\Users\\asha")

For Windows paths and regular expressions, raw strings ignore escapes: r"C:\Users\asha".

Combining strings

Python
first = "Ada"
last = "Lovelace"

first + " " + last          # 'Ada Lovelace'  — concatenation
"ha" * 3                    # 'hahaha'        — repetition
f"{first} {last}"           # 'Ada Lovelace'  — f-string

f-strings

Put an f before the quotes and you can write expressions in curly braces; Python replaces each with its value:

Python
name = "Asha"
age = 29
print(f"{name} is {age} years old.")
print(f"In ten years: {age + 10}")
print(f"Name in capitals: {name.upper()}")

f-strings are the clearest way to build text, and they convert numbers automatically — no str() needed, unlike +:

Python
"Age: " + age        # TypeError: can only concatenate str (not "int") to str
f"Age: {age}"        # 'Age: 29'

They can also format numbers (f"{price:.2f}") — see Formatting output.

Length

Python
len("Python")       # 6
len("")             # 0 — the empty string
len("a b")          # 3 — spaces count

Indexing: one character

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

Indexing and slicing a string. In word = “PYTHON”, the letters P, Y, T, H, O and N have indexes 0 to 5 and negative indexes -6 to -1. word[0] is ‘P’, word[-1] is ‘N’, word[0:2] is ‘PY’, word[2:] is ‘THON’, word[:-2] is ‘PYTH’ and word[::-1] is ‘NOHTYP’. A slice [start:stop] includes start but stops before stop.

Python
word = "PYTHON"
word[0]       # 'P'
word[5]       # 'N'
word[-1]      # 'N' — the last character
word[-2]      # 'O'
word[6]       # IndexError: string index out of range

Slicing: part of a string

word[start:stop] takes the characters from start up to — but not including — stop:

Python
word[0:2]     # 'PY'
word[2:5]     # 'THO'
word[:3]      # 'PYT'   — from the start
word[3:]      # 'HON'   — to the end
word[:]       # 'PYTHON' — a copy of the whole thing
word[::2]     # 'PTO'   — every second character (the third number is the step)
word[::-1]    # 'NOHTYP' — backwards

Why does the stop position not count? Because then word[:3] + word[3:] is always the whole string, and word[a:b] has exactly b - a characters. Slices never raise errors for out-of-range positions; they just return what exists.

Strings are immutable

You can’t change a string in place:

Python
word = "Python"
word[0] = "J"    # TypeError: 'str' object does not support item assignment

Instead, build a new string:

Python
word = "J" + word[1:]     # 'Jython'

The same goes for string methods: they return a new string and leave the original alone.

Python
name = "asha"
name.upper()       # 'ASHA' — but name is still 'asha'
name = name.upper()   # keep the result by reassigning

A first look at methods

A method is a function that belongs to a value, called with a dot:

Python
"hello".upper()           # 'HELLO'
"HELLO".lower()           # 'hello'
"ada lovelace".title()    # 'Ada Lovelace'
"ada".capitalize()        # 'Ada'
"  hi  ".strip()          # 'hi'
"banana".count("a")       # 3
"Py" in "Python"          # True — 'in' checks for a substring

String methods in chapter 7 covers many more.

Remember: indexes start at 0, slices stop before the stop position, and string methods give you a new string — they never change the old one.

Exercise

Fun with a name

Given first = "ada" and last = "lovelace": (1) build the full name with a capital first letter on each part using an f-string, and print Full name: Ada Lovelace; (2) print the initials A.L.; (3) print how many letters the full name has, not counting the space; (4) print the last name backwards; (5) print the first three letters of the last name in upper case. Use indexing, slicing, len() and string methods — no loops needed.

Python
first = "ada"
last = "lovelace"

# 1. Full name with capitals, using an f-string

# 2. Initials

# 3. Number of letters (no space)

# 4. Last name backwards

# 5. First three letters of the last name, upper case

Summary

  • Strings hold text in single, double or triple quotes; use \n for a new line and \" or the other quote type for quotes inside.
  • f-strings like f"Hi {name}" insert values into text — the clearest way to build strings.
  • len(s) counts characters; s[0] is the first, s[-1] the last.
  • Slices s[start:stop:step] take part of a string; the stop position is not included.
  • Strings are immutable: methods like upper() return a new string rather than changing the original.