In the previous lesson, you learned how to access and extract characters from strings using indexing and slicing. While indexing and slicing allow you to retrieve parts of a string, Python also provides many built-in functions specifically designed for modifying, searching, and analyzing text. These built-in functions are called string methods.
String methods make text processing easier and more efficient. Whether you are converting text to uppercase, removing extra spaces, searching for words, replacing characters, or validating user input, string methods help you perform these tasks with just a single line of code.
Python provides dozens of useful string methods that are widely used in web development, automation, data analysis, machine learning, and software development.
In this lesson, you will learn what string methods are, why they are useful, and how to use some of the most common methods such as upper(), lower(), title(), capitalize(), and swapcase().
After completing this lesson, you will be able to:
upper(), lower(), title(), capitalize(), and swapcase().String methods are built-in functions that perform specific operations on strings.
These methods allow you to modify, search, validate, or format text without writing complex code.
String methods are called using the dot (.) operator.
string.method()
language = "python"
print(language.upper())
Output
PYTHON
The upper() method converts all lowercase letters into uppercase letters.
Without string methods, performing text operations would require lengthy code.
String methods simplify common tasks such as:
These operations are frequently used while processing user input, files, databases, and web data.
Every string method is called using the dot operator.
course = "python programming"
print(course.upper())
Output
PYTHON PROGRAMMING
The original string remains unchanged because string methods return a new string.
upper() MethodThe upper() method converts every lowercase character into uppercase.
text = "welcome to python"
print(text.upper())
Output
WELCOME TO PYTHON
This method is commonly used when comparing text regardless of letter case.
lower() MethodThe lower() method converts every uppercase letter into lowercase.
text = "PYTHON PROGRAMMING"
print(text.lower())
Output
python programming
This method is useful when performing case-insensitive comparisons.
title() MethodThe title() method converts the first letter of every word into uppercase.
course = "python for data science"
print(course.title())
Output
Python For Data Science
This method is useful for formatting names and headings.
capitalize() MethodThe capitalize() method converts only the first character of the string into uppercase while converting the remaining characters into lowercase.
message = "python PROGRAMMING"
print(message.capitalize())
Output
Python programming
Only the first character becomes uppercase.
swapcase() MethodThe swapcase() method reverses the case of every letter.
text = "Python Programming"
print(text.swapcase())
Output
pYTHON pROGRAMMING
Every letter changes its case.
Strings in Python are immutable.
This means string methods never modify the original string. Instead, they create and return a new string.
language = "python"
language.upper()
print(language)
Output
python
The original string remains unchanged because the returned value was not stored.
language = "python"
language = language.upper()
print(language)
Output
PYTHON
The new string replaces the original variable.
Suppose you want to store a student’s name in proper title case.
student = "rahul sharma"
student = student.title()
print(student)
Output
Rahul Sharma
This improves the appearance of user-entered data.
Consider the following program.
text = "python"
result = text.upper()
print(result)
Execution Steps
"python".upper() method is called.result.Output
PYTHON
String methods always return a new string because strings are immutable.
Write upper(), not upper.
title() with capitalize()title() capitalizes every word, whereas capitalize() changes only the first character of the entire string.
Store the returned string in a variable if you want to use the modified result.
swapcase() Instead of upper() or lower()Remember that swapcase() reverses the existing case instead of converting everything to one case.
In this section, you learned what Python string methods are and why they simplify text processing. You explored the upper(), lower(), title(), capitalize(), and swapcase() methods, understood how they return new strings, and learned how string immutability affects their behavior. You also reviewed common beginner mistakes and the execution flow of string methods. In the next section, you will explore additional string methods such as strip(), replace(), find(), index(), count(), startswith(), and endswith() for searching and modifying text efficiently.
In the previous section, you learned how to convert the case of strings using methods such as upper(), lower(), title(), capitalize(), and swapcase(). Python also provides many useful methods for removing spaces, replacing text, searching within strings, and checking whether a string starts or ends with specific characters.
These methods are widely used in data cleaning, form validation, web applications, automation, and text processing.
strip() MethodThe strip() method removes whitespace from both the beginning and the end of a string.
text = " Python Programming "
print(text.strip())
Output
Python Programming
Only leading and trailing spaces are removed. Spaces inside the string remain unchanged.
lstrip() MethodThe lstrip() method removes whitespace only from the left side of a string.
text = " Python"
print(text.lstrip())
Output
Python
rstrip() MethodThe rstrip() method removes whitespace only from the right side of a string.
text = "Python "
print(text.rstrip())
Output
Python
replace() MethodThe replace() method replaces one substring with another.
string.replace(old, new)
text = "I love Java"
print(text.replace("Java", "Python"))
Output
I love Python
The original string remains unchanged because replace() returns a new string.
find() MethodThe find() method returns the index of the first occurrence of a substring.
If the substring is not found, it returns -1.
text = "Python Programming"
print(text.find("Program"))
Output
7
text = "Python"
print(text.find("Java"))
Output
-1
index() MethodThe index() method also returns the position of a substring.
Unlike find(), it raises an error if the substring does not exist.
text = "Python Programming"
print(text.index("Program"))
Output
7
text = "Python"
print(text.index("Java"))
Output
ValueError: substring not found
find() and index()find() |
index() |
|---|---|
| Returns the index if found. | Returns the index if found. |
Returns -1 if not found. |
Raises ValueError if not found. |
| Safer when searching optional text. | Useful when the substring must exist. |
count() MethodThe count() method returns the number of times a substring appears in a string.
text = "Python Python Java Python"
print(text.count("Python"))
Output
3
startswith() MethodThe startswith() method checks whether a string begins with a specified substring.
filename = "report.pdf"
print(filename.startswith("report"))
Output
True
print(filename.startswith("data"))
Output
False
endswith() MethodThe endswith() method checks whether a string ends with a specified substring.
filename = "report.pdf"
print(filename.endswith(".pdf"))
Output
True
print(filename.endswith(".doc"))
Output
False
Suppose a user accidentally enters extra spaces while typing an email address.
email = " student@gmail.com "
email = email.strip()
print(email)
Output
student@gmail.com
The strip() method removes unwanted spaces before validation or storage.
Consider the following program.
text = "Python Programming"
position = text.find("Program")
print(position)
Execution Steps
"Python Programming".find() method searches for the substring "Program".position.Output
7
find() with index()Remember that find() returns -1, while index() raises an error when the substring is missing.
strip() to Remove Spaces Inside a Stringstrip() removes only leading and trailing whitespace.
replace() Returns a New StringAssign the result to a variable if you want to keep the modified text.
Methods such as find(), index(), startswith(), and endswith() are case-sensitive.
count() Counts Overlapping MatchesThe count() method counts only non-overlapping occurrences.
In this section, you learned how to clean, search, and modify strings using Python methods such as strip(), lstrip(), rstrip(), replace(), find(), index(), count(), startswith(), and endswith(). You explored their syntax, practical examples, execution flow, and common beginner mistakes. In the next section, you will learn additional string methods such as split(), join(), isalpha(), isdigit(), isalnum(), isspace(), center(), ljust(), and rjust(), along with real-world text-processing examples.
Python provides several additional string methods that help split text into smaller parts, combine multiple strings, validate user input, and format text for better presentation. These methods are widely used in data cleaning, form validation, report generation, automation, and web development.
In this section, you will learn how to use split(), join(), isalpha(), isdigit(), isalnum(), isspace(), center(), ljust(), and rjust() through practical examples.
split() MethodThe split() method divides a string into a list using a specified separator.
string.split(separator)
text = "Python,Java,C++"
languages = text.split(",")
print(languages)
Output
['Python', 'Java', 'C++']
If no separator is specified, split() separates words using whitespace.
sentence = "Python Programming Language"
words = sentence.split()
print(words)
Output
['Python', 'Programming', 'Language']
join() MethodThe join() method combines elements of an iterable into a single string.
words = ["Python", "Programming", "Language"]
result = " ".join(words)
print(result)
Output
Python Programming Language
You can use any separator while joining strings.
items = ["Apple", "Banana", "Orange"]
print(", ".join(items))
Output
Apple, Banana, Orange
isalpha() MethodThe isalpha() method checks whether a string contains only alphabetic characters.
print("Python".isalpha())
print("Python123".isalpha())
Output
True
False
isdigit() MethodThe isdigit() method checks whether a string contains only digits.
print("2026".isdigit())
print("20A6".isdigit())
Output
True
False
isalnum() MethodThe isalnum() method checks whether a string contains only letters and numbers.
print("Python2026".isalnum())
print("Python 2026".isalnum())
Output
True
False
Spaces and special characters cause the method to return False.
isspace() MethodThe isspace() method checks whether a string contains only whitespace characters.
print(" ".isspace())
print(" Python ".isspace())
Output
True
False
center() MethodThe center() method aligns text in the center of a specified width.
text = "Python"
print(text.center(20))
Output
Python
Python adds spaces equally on both sides.
ljust() MethodThe ljust() method aligns text to the left.
text = "Python"
print(text.ljust(15))
Output
Python
rjust() MethodThe rjust() method aligns text to the right.
text = "Python"
print(text.rjust(15))
Output
Python
username = "Rahul"
if username.isalpha():
print("Valid Name")
else:
print("Invalid Name")
Output
Valid Name
age = "25"
if age.isdigit():
print("Valid Age")
else:
print("Invalid Age")
Output
Valid Age
record = "101,Rahul,Delhi"
data = record.split(",")
print(data)
Output
['101', 'Rahul', 'Delhi']
fields = ["101", "Rahul", "Delhi"]
record = ",".join(fields)
print(record)
Output
101,Rahul,Delhi
Consider the following program.
sentence = "Python Programming Language"
words = sentence.split()
print(words)
Execution Steps
split() method is called.words.Output
['Python', 'Programming', 'Language']
split() for Parsing DataIt is ideal for processing CSV files, log files, and user input.
join() Instead of String Concatenation in Loopsjoin() is faster and more efficient when combining multiple strings.
Methods such as isalpha(), isdigit(), and isalnum() help prevent invalid input.
center(), ljust(), and rjust() improve the readability of console output.
Store the returned value if you want to use the modified result.
join() on a single string instead of an iterable.split() to return a string instead of a list.isdigit() for negative or decimal numbers.isalnum() or isalpha().In this section, you learned how to split and combine strings using split() and join(), validate input using isalpha(), isdigit(), isalnum(), and isspace(), and align text using center(), ljust(), and rjust(). You also explored practical examples, execution flow, best practices, and common beginner mistakes. In the final section, you will review the complete lesson through a summary, key takeaways, frequently asked questions, coding exercises, interview questions, a mini project, and a preview of the next lesson on Python String Formatting (format() & f-Strings).
In this lesson, you learned how Python string methods simplify text processing by providing built-in functions for modifying, searching, validating, splitting, joining, and formatting strings. Unlike indexing and slicing, which retrieve parts of a string, string methods perform specific operations that make programs shorter, cleaner, and easier to understand.
You explored methods for changing letter case such as upper(), lower(), title(), capitalize(), and swapcase(). You also learned methods for cleaning text like strip(), lstrip(), and rstrip(), along with search and replacement methods including replace(), find(), index(), count(), startswith(), and endswith().
Finally, you studied methods for splitting and joining strings, validating user input, and aligning text using split(), join(), isalpha(), isdigit(), isalnum(), isspace(), center(), ljust(), and rjust().
These methods are among the most frequently used features in Python programming and are essential for working with user input, files, databases, reports, APIs, and text-based data.
upper(), lower(), title(), and capitalize() change letter case.strip(), lstrip(), and rstrip() remove unwanted whitespace.replace() replaces one substring with another.find() returns -1 if the substring is not found, while index() raises a ValueError.split() converts a string into a list, and join() combines multiple strings into one.isalpha(), isdigit(), isalnum(), and isspace() help validate user input.center(), ljust(), and rjust() improve text alignment in reports and console applications.Python string methods are built-in functions that perform operations such as modifying, searching, validating, and formatting strings.
No. Strings are immutable, so string methods always return a new string.
find() and index()?find() returns -1 when the substring is not found, whereas index() raises a ValueError.
split() method?The split() method divides a string into a list based on a separator.
join() method?The join() method combines elements of an iterable into a single string using a specified separator.
The isalpha() method returns True if all characters are alphabetic.
The strip() method removes whitespace from both ends of a string.
center(), ljust(), and rjust() are used to align text within a specified width.
upper().lower().replace().count()..pdf.upper() and title()?replace() work?find() and index().split() method?join() method work?startswith() and endswith()?Create a Python program that performs common text-processing operations using string methods.
Your program should:
-).Enter Name: rahul sharma
Upper Case : RAHUL SHARMA
Lower Case : rahul sharma
Title Case : Rahul Sharma
Capitalized : Rahul sharma
Enter Sentence: Python is easy to learn
Word Count : 5
Joined Sentence : Python-is-easy-to-learn
Enter Age: 25
Valid Age : True
Congratulations! You have successfully learned Python String Methods. You now understand how to modify, search, validate, split, join, and format strings using Python’s built-in methods. These techniques are essential for text processing, data cleaning, automation, file handling, web development, and many real-world programming tasks.
In the next lesson, you will learn Python String Formatting (format() & f-Strings): Complete Guide for Beginners. You will explore string concatenation, the format() method, positional and keyword arguments, number formatting, floating-point precision, currency formatting, percentage formatting, alignment, padding, and modern f-Strings for writing clean and readable Python code.