Text is everywhere in computing — usernames, messages, web pages, passwords, file names. In programming, text data is stored as a string. A string is a sequence of characters enclosed in quotes. Understanding how to work with strings is essential for almost every real-world program.
Creating Strings
In Python you can use single or double quotes interchangeably:
name = "Alice"
message = 'Hello, world!'
empty = ""
For strings that contain a quote character, use the opposite style:
quote = "It's a great day!"
title = 'He said "Hello"'
String Length and Indexing
len() gives the number of characters. You can access individual characters using their index (position), starting from 0:
word = "Python"
print(len(word)) # 6
print(word[0]) # P
print(word[1]) # y
print(word[-1]) # n (last character)
Indexing starts at 0, not 1. The last character is always at index len(word) - 1, or more conveniently at index -1. Negative indices count from the end.
Slicing
A slice extracts a portion of a string:
word = "Computing"
print(word[0:4]) # Comp (indices 0, 1, 2, 3)
print(word[4:]) # uting (from index 4 to end)
print(word[:4]) # Comp (from start to index 4)
print(word[::2]) # Cmuin (every second character)
The slice syntax is string[start:stop:step], and like range(), the stop index is not included.
Common String Methods
Python strings come with many built-in methods:
| Method | What it does | Example |
|---|---|---|
.upper() | Converts to uppercase | "hello".upper() → "HELLO" |
.lower() | Converts to lowercase | "HELLO".lower() → "hello" |
.strip() | Removes leading/trailing spaces | " hi ".strip() → "hi" |
.replace(old, new) | Replaces part of string | "abc".replace("b","x") → "axc" |
.split(sep) | Splits into a list | "a,b,c".split(",") → ["a","b","c"] |
.startswith(s) | Checks beginning | "hello".startswith("he") → True |
.count(s) | Counts occurrences | "banana".count("a") → 3 |
email = " [email protected] "
clean = email.strip().lower()
print(clean) # [email protected]
String methods do NOT change the original string — they return a new one. Strings in Python are immutable. Always store the result: clean = email.strip(), not just email.strip().
F-Strings (Formatted String Literals)
The cleanest way to embed values inside a string is using an f-string:
name = "Sam"
score = 95
print(f"{name} scored {score} out of 100.")
# Sam scored 95 out of 100.
Put an f before the opening quote and place variable names (or any expression) inside curly braces.
F-strings require Python 3.6 or newer. If you see a SyntaxError on an f-string, check which version of Python you are using.
Looping Over a String
Because a string is a sequence, you can loop through it:
count = 0
for char in "Mississippi":
if char == "s":
count += 1
print(f"Found {count} letter s") # Found 4 letter s
Practice Problems
What does 'Hello World'.lower().replace('o', '0') produce?
Show answer
Given word = 'elephant', how would you extract just 'ela' using slicing?