String is a sequence of characters (letters, numbers, or symbols). Strings are one of the most common data types you'll work with in Python, whether you're cleaning user input, parsing files, or building web applications. Python gives you a rich set of built-in string methods that make text manipulation fast and readable, without needing extra libraries. This guide walks through the most useful ones, grouped by what they actually help you do.
Strings as sequence
String is a list of characters in an ordered sequence.
Key Features of a string as sequence
- Ordered - Each character in a string occupies a specific position
- Indexed - You can access individual characters in a string using an index number.
- Iterable - You can loop through each character in a string.
- Immutable - Every string is immutable, therefore it cannot be modified but returns a new string.
Slicing - Slicing a string is extracting part of it without modifying the string. This uses index position. Counting characters in a string starts with [0] and the end is [-1] and [::-1] reverses the substring.
city = 'Nairobi'
print(city[0]) # N -- the first character
print(city[-1]) # i -- the last character
print(city[:-1]) # Nairob -- all characters excluding the last character.
print(city[0:3]) # Nai -- slices from the first character upto 2
print(city[3:]) # robi -- slices from the character in 3rd position to the end
print(city[::-1]) # iboriaN -- reverses the string.
Concatenation - is the process of joining together two or more strings to form one string. It uses a + sign to join the strings.
city1 = 'Nairobi'
city2 = 'Kisumu'
city3 = 'Mombasa'
city = city1 + ',' + city2 + ' and ' + city3
print(city) # Nairobi, Kisumu and Mombasa
Changing case
String methods lets you standardize text before comparing it, or for display formatting.
There is;
-
upper()- converts all characters to uppercase. -
lower()- converts all characters to lowercase. -
capitalize()- capitalizes only the first letter of the whole string(use it for sentences). -
title()- capitalizes the first letter of every word(use it for names or headings). -
swapcase()- it swaps cases of the strings i.e. (lowercase becomes uppercase and vice versa).
Examples
raw_name = 'bRIAN oTIENO'
print(raw_name.upper()) # BRIAN OTIENO
print(raw_name.lower()) # brian otieno
print(raw_name.title()) # Brian Otieno
print(raw_name.swapcase()) # Brian Otieno
print(raw_name.capitalize()) # Brian otieno
Trimming and cleaning whitespace
Text from files, forms, or user input often comes with unwanted spaces, tabs, or new lines, These methods clean it up.
-
strip()- removes spaces from both sides. -
lstrip()- removes spaces from left side only. -
rstrip()- removes spaces from right side only.
name = ' Python '
print(name.strip()) # Python
print(name.lstrip()) # Python '
print(name.rstrip()) # ' Python
strip() can also be used to remove characters instead of whitespaces.
code = "----Promo2025----"
print(code.strip('-')) # Promo2025
Search and Replacing Inside Strings
These methods let you check for the presence or position of substrings.
-
in- it is the simple member check with yes/no. -
find()- returns the lowest index where the value is found. -
index()- works like find but crashes with a value error if the text is not there. -
count()- returns the total number of occurrences of a substring. -
replace()- replaces occurrences of the substring with another one
text = "Learning Python is fun."
print('Python' in text) # True
print('SQL' in text) # False
text = "Learning Python is fun."
print(text.find('Python')) # 9 index where the word starts
print(text.find('SQL')) # -1 because SQL is not found instead of crashing it return -1
text = "Learning Python is fun."
print(text.index('Python')) # 9 index where the word starts
print(text.index('SQL')) # it crashes and gives a valueError
Use find() when a missing substring is a normal case you want to handle gracefully, and index() when a missing substring should raise an error and stop execution.
text = "Learning Python is fun."
print(text.count('i')) # 2 - number of occurrence
text = "Learning Python is fun."
new_text = text.replace('Python','SQL')
print(new_text) #Learning SQL is fun.
Splitting and joining
Split() turns a string into a list, .join() does the reverse. Together they help with parsing tasks.
Split():
sentence = "Moses is learning Python in Nairobi"
words = sentence.split()
print(words) # ['Moses', 'is', 'learning', 'Python', 'in', 'Nairobi']
Split() can be used with a custom separator.
csv_line = "a,b,c,d"
fields = csv_line.split(",") # ['a', 'b', 'c', 'd']
There's also splitlines(), which is useful when processing multi-line text:
notes = "Buy bread\nPay rent\nCall Mum"
lines = notes.splitlines()
print(lines) # ['Buy bread', 'Pay rent', 'Call Mum']
.join():
words = ['Moses', 'is', 'learning', 'Python', 'in', 'Nairobi']
sentence = ' '.join(words)
print(sentence) # Moses is learning Python in Nairobi
notes = ['Buy bread', 'Pay rent', 'Call Mercy']
lines = '\n'.join(notes)
print(lines) # It outputs each item in its own line.
. join() can also be used to clean spaces between strings where strip cannot.
dirty = " Brian , 24 , Nairobi "
clean = " ".join(dirty.split())
print(clean) # Brian , 24 , Nairobi
name = 'Python Programming'
clean_name = " ".join(name.split())
print(clean_name) # Python Programming
Checking string content
These return True or False and are especially handy for validating input.
-
isdigit()- true if all characters are digits. -
isalnum()- true if all characters are alphabets and numbers. -
isalpha()- true if all characters are alphabets. -
isupper()- true if all characters are uppercase. -
islower()- true if all characters are lowercase.
print("12345".isdigit()) #True
print("Amina".isdigit()) #False
print("Amina23".isalnum()) #True
print("Amina 123".isalnum()) #False (there is space)
print("Amina".isalpha()) #True
print("Amina234".isalpha()) #False
print("amina".islower()) #True
print("AmIna".islower()) #False
print("AMINA".isupper()) #True
Example of how it is used to validate inputs.
while True:
age = input('Enter your age: ')
if age.isdigit(): #checks if it is a digit
age = int(age)
print(f"You are {age} years old.")
break # stops once you enter a valid age
else:
print('That is not a valid whole number. Please try again.')
Prefixes and Suffixes
This checks the boundaries of a string and returns True or False.
phone = "0712345678"
print(phone.startswith('07')) #True
print(phone.startswith('01')) #False
print(phone.endswith('678')) #True
Padding and Formating
This is used to make the code look clean and aligned.
-
{value: <width}- left - aligns the string inside a specific width, padding the rest. -
{value: >width}- right-aligns the string inside a specific width, padding the rest. -
{value: ^width}- center- align the string inside a specific width, padding the rest.
name = 'String'
print(f"[{name:<10}]") # [String ]
print(f"[{name:>10}]") # [ String]
print(f"[{name:^10}]") # [ String ]
It can also be used to pad specific characters on a number
number = 50
print(f"{number:=>5}") # ===50
The zfill() method is a simpler option when you just need zero-padding:
receipt_no = "42"
print(f"Receipt #{receipt_no.zfill(5)}") # Receipt #00042
Formatting in Python is handled by f-strings for readability.
Number and currency formating
- Controlling decimals - rounds the value to the specified number i.e. {val:.2f} rounds to two decimal places
price = 349.6789
print(f"KES {price:.2f}") # KES 349.68
- Thousands separator - adds a comma to large numbers
salary = 1450000
print(f"KES {salary:,}") # KES 1,450,000
- Combining decimals, currency and thousand separator
salary = 1455678.986
print(f"KES {salary:,.2f}") # KES 1,455,678.99
Combining all methods: A Small Example
Here's how several of these methods might combine in a realistic task, cleaning and validating a list of email addresses:
raw_emails = " Alice@Example.com, BOB@test.org ,carol@site.net "
emails = [e.strip().lower() for e in raw_emails.split(",")]
print(emails)
# ['alice@example.com', 'bob@test.org', 'carol@site.net']
for email in emails:
if "@" in email and email.endswith((".com", ".org", ".net")):
print(f"{email} looks valid")
Conclusion
You don't need to memorize every string method to write good Python, but knowing this core set will cover the vast majority of everyday text processing you'll encounter, from cleaning user input to parsing files and generating readable output.
Top comments (0)