Skip to content

Beginner · Text and decisions · topic 5 of 50 · 20 min

Strings: working with text

Explanation

A string is text inside quotes, like "Mumbai". You can measure it with len(), join strings with + and repeat them with *. Each character has a position number starting at 0, so you can pick one character or cut out a slice.

What is a string?

A string is a piece of text: a name, a city, a message, even a phone number written in quotes. In Python the type of a string is str. You can write a string with single quotes or double quotes. Both mean the same thing.

python
city = "Mumbai"
food = 'vada pav'
print(city, food)
print("It's hot today")
note = """Line one
Line two"""
print(note)
Single and double quotes work the same. Use double quotes when the text has an apostrophe. Triple quotes let a string cover many lines.
Think of it like this: Think of a string as a train. Each coach is one character: a letter, a digit, a space or a symbol. The coaches stay in a fixed order, and every coach has a number painted on it, starting from 0 at the engine.

Length, joining and repeating: len() tells you how many characters a string has. Spaces count as characters too. The + sign joins two strings into one; joining is also called concatenation. The * sign repeats a string a number of times.

python
name = "Priya"
print(len(name))
full = "Priya" + " " + "Sharma"
print(full)
print(len(full))
print("-" * 20)
print("ha" * 3)
Shows 5, Priya Sharma, 12, a line of 20 dashes, and hahaha.

Indexing: picking one character

An index is the position number of a character. Python starts counting at 0, so the first character is at index 0. Negative indexes count from the end: -1 is the last character, -2 the one before it.

CharacterPYTHON
Index from the start012345
Index from the end-6-5-4-3-2-1
python
word = "PYTHON"
print(word[0])   # first character: P
print(word[2])   # third character: T
print(word[-1])  # last character: N
print(word[-2])  # second from the end: O
Square brackets after a string pick one character by its index.

Slicing: cutting out a piece

A slice is a piece of a string. You write [start:stop]. Python starts at index start and stops just BEFORE index stop. Leave out start to begin at the beginning; leave out stop to go to the end. An optional third number, the step, jumps over characters.

python
pnr = "4521367890"
print(pnr[0:3])   # 452
print(pnr[3:])    # 1367890
print(pnr[:4])    # 4521
print(pnr[-4:])   # 7890, the last four
print(pnr[::2])   # 42379, every second digit
print(pnr[::-1])  # 0987631254, reversed
Slices of a 10-digit PNR number. A step of -1 reads the string backwards.

Strings are immutable. Immutable means "cannot be changed after it is made". You cannot replace one character inside a string. Instead, you build a new string and store it in the variable.

python
name = "ravi"
name = "R" + name[1:]
print(name)
Shows Ravi. We made a new string from "R" plus the rest of the old one.

Turning numbers into text and text into numbers

str() turns a value into a string. int() turns a string of digits into a whole number, and float() turns it into a decimal number. You need these because Python never mixes text and numbers on its own.

python
age = 21
print("Age: " + str(age))
marks = "85"
print(int(marks) + 5)
print(float("99.5"))
Shows Age: 21, then 90, then 99.5.
Careful: You cannot join a string and a number with +. "Age: " + 21 stops with TypeError: can only concatenate str (not "int") to str. Turn the number into text first with str(21), or use an f-string, which you will learn in the next topic.
Tip: int("12") gives 12, but "12" + "3" gives "123", because joining two strings just puts them side by side. Check whether your values are numbers or text before you use +.

Watch the lesson

Strings: working with text · 1/7

Strings = text in quotes

In this lesson you will learn about strings. A string is text inside quotes, like a name or a city.

Prefer a video by a teacher? Find free videos on “python strings indexing slicing tutorial for beginners” on YouTube ↗

In real life: Hiding a bank account number

When Rahul checks his bank app, it shows only the last four digits of his account number and hides the rest with X. The app does this with a slice and string repeating: X times the hidden length, plus the last four characters.

python
account = "50100234567891"
hidden = len(account) - 4
masked = "X" * hidden + account[-4:]
print(masked)
Shows XXXXXXXXXX7891.

Practice (0/3 done)

Task 1 · Code · Python

Write a function initials(first, last) that returns the first letter of each name followed by a dot. Example: initials("Rahul", "Sharma") returns "R.S."

Task 2 · Code · Python

Write a function mask_number(number) that hides every character except the last 4 with X. Example: mask_number("9876543210") returns "XXXXXX3210". If the number has only 4 characters, nothing is hidden.

Task 3 · Code · Python

Write a function price_tag(item, price) that returns a sentence like "Tea costs Rs 15". item is a string and price is a whole number.

Quick quiz

Question 1

1.What is "PYTHON"[0]?

Question 2

2.What does len("India 2024") give?

Question 3

3.What is "Mumbai"[1:4]?

Question 4

4.What does "ab" * 3 give?

Question 5

5.What happens when you run "Total: " + 50?

Read more (free)

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

← Previous: Numbers and maths