DEV Community

Cover image for Mastering Python String Methods
Alex Murithi
Alex Murithi

Posted on

Mastering Python String Methods

Python String Methods: Indexing, Slicing, Case, Splitting, Joining, and More
Strings are one of the most common data types in Python - and they come with powerful built-in methods for manipulation, formatting, and validation.

1. Indexing and Slicing

Strings are sequences, so you can access individual characters or slices using indexes.

city = 'Nairobi'
print(city[0])      # First character
print(city[-1])     # Last character
Enter fullscreen mode Exit fullscreen mode

Output

N
i
Enter fullscreen mode Exit fullscreen mode

Slicing

city = 'Nairobi'
print(city[0:3])    # Nai
print(city[3:])     # robi
print(city[::-1])   # Reverse
Enter fullscreen mode Exit fullscreen mode

Output

Nai
robi
iboriaN
Enter fullscreen mode Exit fullscreen mode

2. Concatenation and Repetition

You can combine strings with + and repeat them with *.

first = 'Nai'
second = 'robi'
print(first + second)
print("=" * 30)
print("Ha" * 3)
Enter fullscreen mode Exit fullscreen mode

Output

Nairobi
==============================
HaHaHa
Enter fullscreen mode Exit fullscreen mode

3. Strings Are Immutable

You can’t change characters directly - you must create a new string.

city = 'Nairobi'
# city[0] = 'K'  # TypeError
city = 'K' + city[1:]
print(city)
Enter fullscreen mode Exit fullscreen mode

Output

Kairobi
Enter fullscreen mode Exit fullscreen mode

4. Changing Case

String methods help standardize text before comparison.

name = 'nancy wanjiku'
print(name.upper())
print(name.lower())
print(name.capitalize())
print(name.title())
Enter fullscreen mode Exit fullscreen mode

Output

NANCY WANJIKU
nancy wanjiku
Nancy wanjiku
Nancy Wanjiku
Enter fullscreen mode Exit fullscreen mode

swapcase()

greeting = 'Hello WORLD'
print(greeting.swapcase())
Enter fullscreen mode Exit fullscreen mode

Output

hELLO world
Enter fullscreen mode Exit fullscreen mode

5. Removing Extra Spaces

name = '   Faith  '
print(len(name))
print(f'[{name.strip()}]')
print(f'[{name.lstrip()}]')
print(f'[{name.rstrip()}]')
Enter fullscreen mode Exit fullscreen mode

Output

9
[Faith]
[Faith  ]
[   Faith]
Enter fullscreen mode Exit fullscreen mode

Removing Specific Characters

code = '###PROMO2025###'
print(code.strip('#'))
Enter fullscreen mode Exit fullscreen mode

Output

PROMO2025
Enter fullscreen mode Exit fullscreen mode

6. Splitting Text

Break a string into a list using split().

sentence = "Python is greater for data"
words = sentence.split()
print(f"Word count: {len(words)}")
Enter fullscreen mode Exit fullscreen mode

Output

Word count: 5
Enter fullscreen mode Exit fullscreen mode

Split by Separator

csv_line = "Moses,23,Nairobi,Data Science"
csv_split = csv_line.split(',')
print(csv_split)
Enter fullscreen mode Exit fullscreen mode

Output

['Moses', '23', 'Nairobi', 'Data Science']
Enter fullscreen mode Exit fullscreen mode

Split Lines

notes = "Buy bread\nGo for walk\nRide Bike"
lines = notes.splitlines()
print(lines)
Enter fullscreen mode Exit fullscreen mode

Output

['Buy bread', 'Go for walk', 'Ride Bike']
Enter fullscreen mode Exit fullscreen mode

Practical Example

route_info = 'Route46,Nairobi,50'
r_info = route_info.split(',')
print(f"{r_info[0]} costs KES {r_info[2]}")
Enter fullscreen mode Exit fullscreen mode

Output

Route46 costs KES 50
Enter fullscreen mode Exit fullscreen mode

7. join() - The Opposite of split()

items = ['Bread', 'Milk', 'Sugar']
shopping_text = ','.join(items)
print(shopping_text)
Enter fullscreen mode Exit fullscreen mode

Output

Bread,Milk,Sugar
Enter fullscreen mode Exit fullscreen mode

Custom Separator

parts = ['Nairobi', 'Mombasa', 'Kisumu']
result = " | ".join(parts)
print(result)
Enter fullscreen mode Exit fullscreen mode

Output

Nairobi | Mombasa | Kisumu
Enter fullscreen mode Exit fullscreen mode

Real Use Case - Cleaning Text

dirty = "  Moses,  23  ,  Nairobi  ,  Data Science    "
dirty_list = dirty.split(',')
clean_list = [i.strip() for i in dirty_list]
clean = ','.join(clean_list)
print(clean)
Enter fullscreen mode Exit fullscreen mode

Output

Moses,23,Nairobi,Data Science
Enter fullscreen mode Exit fullscreen mode

8. find(), index(), count(), and replace()

Checking Existence

message = "Your M-pesa transaction of KES 500 was successful."
print('M-pesa' in message)
print('failed' in message)
Enter fullscreen mode Exit fullscreen mode

Output

True
False
Enter fullscreen mode Exit fullscreen mode

Finding Position

print(message.find('KES'))
print(message.find('failed'))
Enter fullscreen mode Exit fullscreen mode

Output

26
-1
Enter fullscreen mode Exit fullscreen mode

Counting and Replacing

text = "banana"
print(text.count('a'))

new_message = message.replace('successful', 'reversed')
print(new_message)
Enter fullscreen mode Exit fullscreen mode

Output

3
Your M-pesa transaction of KES 500 was reversed.
Enter fullscreen mode Exit fullscreen mode

9. Validation Methods

Check if a string contains digits, letters, or both.

print("12345".isdigit())
print("Joan".isalpha())
print("Joan123".isalnum())
print("Joan 123".isalnum())
Enter fullscreen mode Exit fullscreen mode

Output

True
True
True
False
Enter fullscreen mode Exit fullscreen mode

Input Validation Example

age = input("Enter your age: ")

while not age.isdigit():
    print("Enter a valid whole number")
    age = input("Enter your age: ")

age = int(age)
print(f"You are {age} years old"
)
Enter fullscreen mode Exit fullscreen mode

Sample Output

Enter your age: abc
Enter a valid whole number
Enter your age: 25
You are 25 years old
Enter fullscreen mode Exit fullscreen mode

10. Prefixes, Suffixes, and Alignment

startswith() and endswith()

phone = '0712345678'
print(phone.startswith('07'))
print(phone.endswith('678'))
Enter fullscreen mode Exit fullscreen mode

Output

True
True
Enter fullscreen mode Exit fullscreen mode

Padding and Alignment

name = 'Otieno'
print(f"[{name:<10}]")  # Left align
print(f"[{name:>10}]")  # Right align
print(f"[{name:^10}]")  # Center align
Enter fullscreen mode Exit fullscreen mode

Output

[Otieno    ]
[    Otieno]
[  Otieno  ]
Enter fullscreen mode Exit fullscreen mode

Table Formatting Example

employee = [
    ("Brian", "Developer", 102000),
    ("Otieno", "Finance", 78000),
    ("Njeri", "Data Engineer", 95000)
]

print(f"{'Name':<12} {'Role':<18} {'Salary':>12}")
print("-" * 40)
for name, role, salary in employee:
    print(f"{name:<12} {role:<18} Ksh {salary:>8}")
Enter fullscreen mode Exit fullscreen mode

Output

Name         Role               Salary
----------------------------------------
Brian        Developer       Ksh  102000
Otieno       Finance         Ksh   78000
Njeri        Data Engineer   Ksh   95000
Enter fullscreen mode Exit fullscreen mode

Conclusion

String methods make text manipulation in Python simple and powerful.
You can:

Slice and combine text easily

Clean and format data

Validate user input

Search and replace efficiently

Mastering these methods will make your Python programs cleaner, smarter, and more professional.

Top comments (0)