// python · beginner
Working with Strings in Python: Slicing, Methods and Formatting
Learn how Python strings work, how to index and slice them, the string methods you'll use every day, and how to clean up and format text from users.
Almost every program works with text: names, messages, file contents, web pages. In Python, text is stored as a string. This guide covers everything a beginner needs: picking out characters, cutting strings into pieces, cleaning up messy input, and the handful of methods you’ll use constantly.
Making strings
You can use single or double quotes. They mean the same thing, so pick whichever saves you escaping a quote inside:
greeting = "Hello"
reply = 'She said "hi"'
apostrophe = "It's working"
For text over several lines, use triple quotes:
message = """Line one
Line two
Line three"""
Length and individual characters
len() tells you how many characters a string has. Each character has a position, called an index, starting at 0:
word = "Python"
print(len(word)) # 6
print(word[0]) # P
print(word[5]) # n
print(word[-1]) # n (negative numbers count from the end)
| Character | P | y | t | h | o | n |
|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative index | -6 | -5 | -4 | -3 | -2 | -1 |
Asking for word[6] gives an IndexError, because the last index of a 6-character string is 5.
Slicing: taking part of a string
A slice takes a range of characters with [start:stop]. Like range(), it stops before the stop position:
word = "CodeRunner"
print(word[0:4]) # Code
print(word[4:]) # Runner (from 4 to the end)
print(word[:4]) # Code (from the start to 4)
print(word[-6:]) # Runner (the last six characters)
print(word[::-1]) # rennuRedoC (a step of -1 reverses it)
Slicing never raises an error for positions that are too big; it just gives you as much as exists. That makes it safer than indexing.
Strings can’t be changed
Strings are immutable: you can’t change a character in place.
name = "sam"
name[0] = "S" # TypeError: 'str' object does not support item assignment
Instead, you build a new string and store it:
name = "sam"
name = "S" + name[1:]
print(name) # Sam
The string methods you’ll use most
A method is a function that belongs to a value. You call it with a dot. String methods always return a new string; they never change the original.
text = " Hello, World! "
print(text.strip()) # "Hello, World!" removes spaces at both ends
print(text.lower()) # " hello, world! "
print(text.upper()) # " HELLO, WORLD! "
print(text.replace("World", "Python")) # " Hello, Python! "
| Method | What it does | Example | Result |
|---|---|---|---|
.strip() |
removes whitespace at both ends | " hi ".strip() |
"hi" |
.lower() / .upper() |
changes the case | "Hi".upper() |
"HI" |
.title() |
capitalises each word | "ada lovelace".title() |
"Ada Lovelace" |
.replace(a, b) |
swaps every a for b |
"a-b-c".replace("-", "") |
"abc" |
.split() |
breaks into a list of words | "a b c".split() |
['a', 'b', 'c'] |
.join(list) |
glues a list into one string | ", ".join(["a", "b"]) |
"a, b" |
.startswith(x) |
does it begin with x? |
"python".startswith("py") |
True |
.count(x) |
how many times x appears |
"banana".count("a") |
3 |
.find(x) |
index of x, or -1 if missing |
"banana".find("n") |
2 |
A common beginner mistake is calling a method and forgetting to keep the result:
name = " ava "
name.strip() # does nothing useful: the result is thrown away
name = name.strip() # correct: store the new string
Checking what’s inside
The in keyword asks whether one string appears inside another:
email = "learner@example.com"
if "@" in email:
print("Looks like an email address")
There are also methods that test the whole string, which are useful for checking input:
print("2026".isdigit()) # True
print("abc".isalpha()) # True
print("abc123".isalnum()) # True (letters or digits only)
Cleaning up user input
People type in all sorts of ways: extra spaces, capital letters, mixed case. Normalising input before you compare it saves a lot of bugs:
answer = input("Do you want to continue? (yes/no) ")
answer = answer.strip().lower()
if answer in ("yes", "y"):
print("Carrying on!")
else:
print("Stopping.")
Methods can be chained: .strip() returns a string, so you can call .lower() on it straight away.
Splitting and joining
.split() turns a sentence into a list of words, and .join() does the reverse. Together, they’re great for tidying text:
sentence = "learning python is fun"
words = sentence.split() # ['learning', 'python', 'is', 'fun']
tidy = " ".join(words)
print(tidy) # learning python is fun
You can split on any separator, which is handy for simple data:
row = "Ava,15,Python"
name, age, language = row.split(",")
print(name, language) # Ava Python
Formatting numbers inside text
You met f-strings in the variables guide. They can also line things up and control decimal places:
item = "Notebook"
price = 2.5
print(f"{item:<10}£{price:>6.2f}")
# Notebook £ 2.50
<10 pads the text to 10 characters, aligned left; >6.2f right-aligns the number in 6 characters with 2 decimal places. It’s perfect for printing neat tables.
Mini project: a username generator
first = input("First name: ").strip().lower()
last = input("Last name: ").strip().lower()
year = input("Year you were born: ").strip()
if not year.isdigit() or len(year) != 4:
print("Please enter a four-digit year.")
else:
username = first[:3] + last[:3] + year[-2:]
print(f"Your username is: {username}")
For Ada Lovelace born in 1815, this prints adalov15. Challenge: remove any spaces or hyphens from the names first, so Mary-Jane works too.
Key points
- Strings are text; indexes start at 0, and negative indexes count from the end.
[start:stop]slices stop beforestop;[::-1]reverses.- Strings can’t be changed, so methods return a new string you must store.
.strip().lower()is the go-to clean-up for user input..split()and.join()convert between strings and lists.
Next, learn how to store many values at once in Python Lists for Beginners.