A string is a piece of text, such as a name, a phone number or a whole message. Python strings come with dozens of built-in methods for cleaning, searching and formatting text. Because user input always arrives as text, you will use these methods in almost every program you write.
In this lesson you will learn
- How to index and slice a string
- The most useful string methods:
strip,split,join,replace,findand more - How to build text neatly with f-strings
- Why strings cannot be changed in place
Indexing and Slicing Text
Strings work like lists of characters: index 0 is the first character, -1 the last, and slices use [start:stop:step].
city = "Chattogram"
print(len(city), city[0], city[-1])
print(city[0:5], city[5:], city[::-1])
print(city.upper(), city.lower())
print("gram" in city, city.count("t"))
Output
10 C m
Chatt ogram margottahC
CHATTOGRAM chattogram
True 2
city[::-1] reverses the text. The in operator checks whether one string appears inside another, and count() counts how often a character or word appears.
Cleaning and Searching Text
Real input is messy: extra spaces, odd capital letters, dashes in phone numbers. String methods tidy it up. Each one returns a new string.
raw = " Rahim Uddin , 01711-000000 "
name, phone = [part.strip() for part in raw.split(",")]
print(name.title())
print(phone.replace("-", ""))
print(name.startswith("Rahim"), phone.isdigit(), phone.replace("-", "").isdigit())
print(" | ".join(["CSE", "EEE", "BBA"]))
print(name.find("Uddin"), name.find("Khan"))
Output
Rahim Uddin
01711000000
True False True
CSE | EEE | BBA
6 -1
| Method | What it does |
|---|---|
strip() | Removes spaces (and newlines) from both ends |
split(sep) | Breaks text into a list at each sep |
sep.join(list) | Joins a list of strings with sep between them |
replace(old, new) | Swaps every old for new |
title(), upper(), lower() | Change letter case |
find(sub) | Position of sub, or -1 if missing |
startswith(), endswith() | Check the beginning or end |
isdigit(), isalpha() | Check what kind of characters the text holds |
Notice phone.isdigit() is False because of the dash; after replace("-", "") it is True. That is a simple way to validate a phone number.
f-strings and Immutability
item, qty, unit = "Notebook", 3, 45.5
print(f"{qty} x {item} = {qty * unit:.2f} taka")
print(f"{item:<10}|{qty:>4}|")
word = "python"
try:
word[0] = "P"
except TypeError as err:
print("Error:", err)
print("P" + word[1:])
Output
3 x Notebook = 136.50 taka
Notebook | 3|
Error: 'str' object does not support item assignment
Python
- An f-string puts expressions inside
{}. After a colon you can add a format:.2ffor two decimals,<10to left-align in 10 spaces,>4to right-align. - Strings are immutable:
word[0] = "P"fails. Build a new string instead, as in"P" + word[1:].
Common String Mistakes
- Calling a method and ignoring the result.
name.strip()alone changes nothing; writename = name.strip(). - Joining numbers.
", ".join([1, 2])fails; convert first withmap(str, nums). - Using
index()when the text may be missing. It raisesValueError;find()returns -1 instead. - Building long text with
+in a loop. Collect pieces in a list andjoinonce at the end.
Practice Exercises
Exercise 1. Turn " bangladesh " into "Bangladesh".
Show answer
print(" bangladesh ".strip().capitalize())
Exercise 2. Count the words in "Learn Python one step at a time".
Show answer
print(len("Learn Python one step at a time".split())) # 7
Exercise 3. Check whether "madam" reads the same backwards.
Show answer
word = "madam"
print(word == word[::-1]) # True
Frequently Asked Questions
Are single and double quotes different in Python strings?
No. Both create the same kind of string. Choose the one that avoids escaping quotes inside your text.
How do I put a new line inside a string?
Use \n, as in "line one\nline two", or a triple-quoted string that spans several lines.
Can Python strings hold Bangla text?
Yes. Python 3 strings are Unicode, so Bangla, Arabic, emoji and any other script work without extra setup.
Summary
- Strings index and slice like lists, but cannot be changed in place.
strip,split,join,replaceandfindhandle most text cleaning.- Every method returns a new string; store the result.
- f-strings with format codes produce neat output.
