Python provides many built-in string methods that make it easy to work with text.
Instead of writing everything from scratch, you can use methods to change capitalization, search for text, replace words, split strings, and much more.
Let's look at the most useful ones.
Changing Letter Case
Python provides several methods for changing the case of a string.
upper()
Converts all letters to uppercase.
text = "hello python"
print(text.upper())Output:
HELLO PYTHONlower()
Converts all letters to lowercase.
text = "HELLO PYTHON"
print(text.lower())Output:
hello pythontitle()
Capitalizes the first letter of each word.
text = "hello python world"
print(text.title())Output:
Hello Python Worldcapitalize()
Capitalizes only the first character of the string.
text = "hello python"
print(text.capitalize())Output:
Hello pythonRemoving Extra Spaces
strip()
Removes whitespace from both ends of a string.
text = " Hello Python "
print(text.strip())Output:
Hello PythonThere are also:
text.lstrip() # Removes from the left
text.rstrip() # Removes from the rightThese methods are especially useful when processing user input.
Searching Inside a String
find()
Returns the index of the first occurrence of some text.
text = "I am learning Python"
print(text.find("Python"))Output:
14If the text isn't found, find() returns -1.
count()
Counts how many times a substring appears.
text = "Python is easy. Python is powerful."
print(text.count("Python"))Output:
2Checking a String
Python has several methods that return True or False.
startswith()
Checks whether a string starts with specific text.
text = "Python Programming"
print(text.startswith("Python"))Output:
Trueendswith()
Checks whether a string ends with specific text.
filename = "report.pdf"
print(filename.endswith(".pdf"))Output:
Trueisdigit()
Checks whether all characters are digits.
value = "12345"
print(value.isdigit())Output:
Trueisalpha()
Checks whether all characters are alphabetic.
name = "John"
print(name.isalpha())Output:
TrueReplacing Text
The replace() method replaces one part of a string with another.
text = "I like Java"
text = text.replace("Java", "Python")
print(text)Output:
I like PythonThis is useful when you need to modify text.
Splitting a String
The split() method breaks a string into a list.
text = "Apple Banana Mango"
fruits = text.split()
print(fruits)Output:
['Apple', 'Banana', 'Mango']You can also specify what should be used as the separator:
text = "Apple,Banana,Mango"
fruits = text.split(",")
print(fruits)Output:
['Apple', 'Banana', 'Mango']This is commonly used when processing user input or data.
Joining Strings
join() does the opposite of split(). It combines multiple strings into one string.
fruits = ["Apple", "Banana", "Mango"]
result = ", ".join(fruits)
print(result)Output:
Apple, Banana, MangoThe string before .join() is used as the separator.
Checking the Length
Although len() is a function rather than a string method, it's commonly used with strings.
text = "Python"
print(len(text))Output:
6A Practical Example
Let's say we're getting a username from a user:
username = input("Enter your username: ")
username = username.strip().lower()
if username.startswith("john"):
print("Welcome John!")
else:
print("Welcome!")If the user enters:
JOHN123strip() removes the extra spaces and lower() converts it to lowercase.
So the username becomes:
john123Common String Methods
Here's a handy list of the methods you'll use most often:
Method | Purpose |
|---|---|
| Converts to uppercase |
| Converts to lowercase |
| Capitalizes each word |
| Capitalizes the first character |
| Removes surrounding whitespace |
| Finds the position of text |
| Counts occurrences |
| Replaces text |
| Splits a string into a list |
| Combines strings |
| Checks the beginning |
| Checks the ending |
| Checks for digits |
| Checks for letters |
String methods save us a lot of work. Once you get comfortable with the commonly used ones, you'll be able to clean, search, modify, and process text very easily in Python.