- Join and repeat strings and find their length
- Take parts of a string with indexes and slices
- Use string methods
- Insert values into text and format numbers with f-strings
Messages, names, passwords, news headlines — much of the data programs work with is text. Imagine you are making automatic birthday cards for your classmates: “Happy birthday, Elvin! You are 13 today.” Only the name and the age change from card to card. In this lesson you will learn to work with text and build templates like this in a single line.
Strings
A string (str) is a sequence of characters written in quotes: letters, digits, spaces and symbols. You can join strings with +, repeat them with * and find their length with the len() function.
greeting = 'Hello'
name = 'Aysel'
message = greeting + ', ' + name + '!'
print(message)
print(len(message))
print('Ha' * 3)▸ Expected output
Hello, Aysel! 13 HaHaHa
len() counts spaces and punctuation too, which is why 'Hello, Aysel!' has a length of 13. Some characters are written in a special way: \n inside a string starts a new line. If your text contains an apostrophe, wrap the string in double quotes — then Python will not mistake the apostrophe for the end of the string.
print('First line\nSecond line')
print("It's easy!")▸ Expected output
First line Second line It's easy!
Indexes and slices
Every character in a string has its own number — its index. In Python counting starts at 0: the first character is [0], the second [1], and so on. Negative indexes count from the end: [-1] is the last character.
| Character | P | y | t | h | o | n |
|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative index | -6 | -5 | -4 | -3 | -2 | -1 |
'Python'A slice takes part of a string: word[start:end]. The start index is included, but the end index is not. If you leave one of the numbers out, Python goes from the very beginning or to the very end.
word = 'Python'
print(word[0])
print(word[5])
print(word[-1])
print(word[0:2])
print(word[2:])
print(word[:4])▸ Expected output
P n n Py thon Pyth
String methods
A method is a function that belongs to a type; you call it with a dot after the value: name.upper(). Methods do not change the original string — they return a new one. The most useful ones are:
| Method | What it does | Example |
|---|---|---|
upper(), lower() | makes all letters upper or lower case | 'Baku'.upper() → 'BAKU' |
title() | capitalises the first letter of each word | 'leyla mammadova'.title() → 'Leyla Mammadova' |
strip() | removes spaces at the start and end | ' hi '.strip() → 'hi' |
replace(a, b) | replaces a with b | 'tea'.replace('t', 'p') → 'pea' |
count(x) | counts how many times x appears | 'banana'.count('a') → 3 |
startswith(x) | checks whether the string starts with x | 'Python'.startswith('Py') → True |
city = ' baku '
clean = city.strip()
print(clean.title())
print(clean.upper())
text = 'I like tea. Tea is tasty.'
print(text.lower().count('tea'))
print(text.replace('tea', 'coffee'))
print('tea' in text)
print(text.startswith('I'))▸ Expected output
Baku BAKU 2 I like coffee. Tea is tasty. True True
Notice that replace is case-sensitive, so only the lowercase tea was replaced. For count we first turned the whole text to lowercase with lower() — methods can be chained like this. The in operator checks whether one string appears inside another and gives True or False.
f-strings: templates
The easiest way to put values into text is an f-string. Write the letter f before the opening quote and put a variable or any expression in curly braces {}. Python replaces each pair of braces with its value.
name = 'Elvin'
age = 13
print(f'Happy birthday, {name}! You are {age} today.')
print(f'Next year you will be {age + 1}.')
price = 7.5
print(f'Price: {price:.2f} AZN')▸ Expected output
Happy birthday, Elvin! You are 13 today. Next year you will be 14. Price: 7.50 AZN
{price:.2f} shows the number with exactly 2 digits after the decimal point — perfect for amounts of money. See why this matters in a real receipt:
item = 'Notebook'
qty = 3
unit_price = 2.35
total = qty * unit_price
print(total)
print(f'{item}: {qty} x {unit_price} = {total:.2f} AZN')▸ Expected output
7.050000000000001 Notebook: 3 x 2.35 = 7.05 AZN
The odd 7.050000000000001 in the first line comes from the way computers store decimal numbers in binary. Formatting hides this tiny “tail”.
A user typed their name carelessly: ' aYSEL '. Print three lines: 1) the name without spaces and with only the first letter capitalised (Aysel), 2) the number of letters in the name, 3) the first three letters of the name in capitals.
raw = ' aYSEL '
# 1) name = raw without spaces, in title case
# 2) print name, its length and its first 3 letters in capitals▸ Expected output
Aysel 5 AYS
Build one line of a receipt with an f-string: the item name in capitals, and the price and the total with exactly two digits after the point (:.2f). The result must be NOTEBOOK: 4 x 1.35 = 5.40 AZN. Calculate the total as qty * unit_price.
item = 'Notebook'
qty = 4
unit_price = 1.35
# total = ...
# print the receipt line with an f-string▸ Expected output
NOTEBOOK: 4 x 1.35 = 5.40 AZN
Key points
- A string is a sequence of characters in quotes:
+joins,*repeats andlen()gives the length. - Indexes start at 0, and
[-1]is the last character. - In a slice
[start:end], the end index is not included. - Methods (
upper,strip,replaceand others) return a new string and leave the old one unchanged. - In an f-string the expression in
{}is evaluated and inserted;{x:.2f}shows 2 decimal places.
Check yourself
10 questions. Every correct answer earns XP.
s = 'Python', what is s[1]?