Learn / Beginner / Lesson 5

Strings

11 min Tested on Python 3.15Updated By
In short

A string (str) is text inside quotes, such as "hello". You can read characters by position (text[0]), cut pieces out with slices (text[0:5]) and use methods like .upper(), .strip() and .split(). Strings never change — methods return a new string.

Creating strings

Python
single = 'Python'
double = "It's easy"
multi = """Line one
Line two"""
print(single)
print(double)
print(multi)
Output
Python
It's easy
Line one
Line two

Single and double quotes work the same way — pick the one that avoids clashing with quotes inside the text. Triple quotes allow several lines.

Indexing and slicing

Python
word = "Python"
print(word[0])
print(word[-1])
print(word[0:3])
print(word[2:])
print(word[::-1])
print(len(word))
Output
P
n
Pyt
thon
nohtyP
6
  • Positions start at 0. Negative positions count from the end: -1 is the last character.
  • text[start:stop] includes start but stops just before stop.
  • Leave out start or stop to go from the beginning or to the end. [::-1] reverses.
  • len() gives the number of characters.

Everyday string methods

Python
raw = "  Hello, Python World  "
clean = raw.strip()
print(clean)
print(clean.upper())
print(clean.lower())
print(clean.replace("World", "learners"))
print(clean.split(", "))
print(clean.startswith("Hello"))
print("Python" in clean)
Output
Hello, Python World
HELLO, PYTHON WORLD
hello, python world
Hello, Python learners
['Hello', 'Python World']
True
True

Strings can't be changed in place

Python
name = "asha"
name.upper()
print(name)

name = name.upper()
print(name)
Output
asha
ASHA

Joining and formatting

Python
parts = ["2026", "11", "19"]
print("-".join(parts))

price = 1234.5
print(f"Total: {price:,.2f} EUR")
print(f"{'left':<8}|{'right':>8}|")
Output
2026-11-19
Total: 1,234.50 EUR
left    |   right|

"-".join(list) glues pieces together. Inside an f-string, a format spec after : controls the look: ,.2f adds thousands separators and 2 decimals, <8 and >8 pad to a width of 8.

Practice

Clean up email = " Asha.Rao@Example.COM ": remove the spaces, make it lowercase, then print the cleaned email and, on a second line, only the part after the @.

Expected output:
asha.rao@example.com
example.com
Your code

Quick check

1. What is "Python"[1:4]?

2. After s = "hi" and s.upper(), what is s?

3. What does ", ".join(["a", "b", "c"]) give?

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →