Python String Methods
Learn how to clean, search, modify, split, combine, validate, and format text using Python's powerful built-in string methods.
By the end of this lesson, you will be able to:
- Understand what string methods are.
- Change the case of text.
- Remove unwanted whitespace.
- Search inside strings.
- Replace portions of text.
- Count occurrences of characters or words.
- Split strings into lists.
- Join list elements into strings.
- Validate string content.
- Chain multiple string methods together.
What Are String Methods?
A string method is a built-in operation that allows you to perform a specific task on a string.
Python provides many useful methods for working with text, including methods for changing case, searching, replacing, splitting, joining, and validating strings.
string.method()
name = "python"
print(name.upper())
PYTHON
String methods usually return a new string. They do not modify the original string in place.
lower() & upper()
The lower() method converts letters to
lowercase, while upper() converts letters
to uppercase.
text = "Hello Python"
print(text.lower())
print(text.upper())
hello python HELLO PYTHON
These methods are particularly useful when comparing text without worrying about uppercase or lowercase differences.
answer = "YES"
if answer.lower() == "yes":
print("Confirmed")
capitalize() & title()
capitalize() makes the first character
uppercase and converts the remaining characters
to lowercase.
title() converts the first character of
each word to uppercase.
text = "python programming language"
print(text.capitalize())
print(text.title())
Python programming language Python Programming Language
swapcase()
The swapcase() method changes uppercase
letters to lowercase and lowercase letters to uppercase.
text = "PyThOn"
print(text.swapcase())
pYtHoN
strip()
The strip() method removes leading and
trailing whitespace from a string.
name = " Adnan "
clean_name = name.strip()
print(clean_name)
Adnan
Users may accidentally type spaces before
or after their input. strip()
can clean those spaces.
lstrip() & rstrip()
lstrip() removes whitespace from the
left side, while rstrip() removes
whitespace from the right side.
text = " Python "
print(text.lstrip())
print(text.rstrip())
Python Python
replace()
The replace() method replaces one piece
of text with another.
text = "I like Java"
new_text = text.replace("Java", "Python")
print(new_text)
I like Python
You can also specify how many occurrences should be replaced.
text = "cat cat cat"
print(text.replace("cat", "dog", 2))
dog dog cat
find()
The find() method searches for a substring
and returns the index of its first occurrence.
text = "I love Python"
position = text.find("Python")
print(position)
7
If the substring cannot be found, find()
returns -1.
text = "Python"
print(text.find("Java"))
-1
index()
The index() method also searches for a
substring and returns its position.
text = "I love Python"
print(text.index("Python"))
7
If the text is not found, index()
raises a ValueError, while
find() returns -1.
count()
The count() method tells you how many
times a substring appears in a string.
text = "banana"
print(text.count("a"))
print(text.count("an"))
3 2
startswith() & endswith()
These methods check whether a string starts or ends with a particular piece of text.
filename = "report.pdf"
print(filename.startswith("report"))
print(filename.endswith(".pdf"))
True True
These methods are extremely useful when validating filenames, URLs, usernames, and other text patterns.
split()
The split() method divides a string into
a list of smaller strings.
sentence = "Python is easy to learn"
words = sentence.split()
print(words)
['Python', 'is', 'easy', 'to', 'learn']
By default, whitespace is used as the separator. You can also provide your own separator.
data = "Ali,25,Multan"
parts = data.split(",")
print(parts)
['Ali', '25', 'Multan']
join()
The join() method does the opposite of
split(): it combines strings from an
iterable into one string.
words = ["Python", "is", "powerful"]
sentence = " ".join(words)
print(sentence)
Python is powerful
The string before .join() becomes the
separator.
items = ["Python", "HTML", "CSS"]
print(", ".join(items))
print(" | ".join(items))
print("-".join(items))
Python, HTML, CSS Python | HTML | CSS Python-HTML-CSS
You've reached the end of this lesson.
Review the examples, open the Practice Lab, and mark this lesson complete when you're ready.