Paramclasses Academy - Blog

Tutorials Details

←
Post 8 of 20
→

Python String Methods: upper(), split(), replace() & More

Python String Methods: upper(), split(), replace() & More

October 17, 2026

Python String Methods: upper(), split(), replace() & More

1. Introduction to Python String Methods

Python provides several built-in string methods to manipulate, search, validate, and format text. These methods make it easier to work with names, email addresses, messages, product information, and other text-based data.

String methods return results without changing the original string because Python strings are immutable.

Example

text = "hello python"

print(text.upper())
print(text.title())
print(text.capitalize())

Output:

HELLO PYTHON
Hello Python
Hello python

2. Case Conversion Methods

Case conversion methods change the capitalization of characters.

upper()

Converts all cased characters to uppercase.

text = "learn python"
print(text.upper())

Output: LEARN PYTHON

lower()

Converts all cased characters to lowercase.

text = "LEARN PYTHON"
print(text.lower())

Output: learn python

title()

Converts the first cased character of each word to uppercase.

text = "python programming tutorial"
print(text.title())

Output: Python Programming Tutorial

capitalize()

Converts the first character to uppercase and the remaining characters to lowercase.

text = "pYTHON PROGRAMMING"
print(text.capitalize())

Output: Python programming

swapcase()

Changes uppercase characters to lowercase and lowercase characters to uppercase.

text = "Python Programming"
print(text.swapcase())

Output: pYTHON pROGRAMMING

3. Removing Whitespace

Whitespace includes spaces, tabs, and newline characters.

strip()

Removes whitespace from both ends of a string.

text = "   Python   "
print(text.strip())

Output: Python

lstrip()

Removes whitespace from the left side.

text = "   Python"
print(text.lstrip())

Output: Python

rstrip()

Removes whitespace from the right side.

text = "Python   "
print(text.rstrip())

Output: Python

Practical Use: These methods are useful for cleaning user input before saving it to a database.

4. Replacing Text with replace()

The replace() method returns a new string in which occurrences of one substring are replaced with another.

Syntax

string.replace(old, new, count)
  • old: Text to search for.

  • new: Replacement text.

  • count: Optional maximum number of replacements.

Example 1: Basic Replacement

text = "I like Java"
result = text.replace("Java", "Python")

print(result)

Output: I like Python

Example 2: Replace Spaces

text = "Python is easy to learn"
print(text.replace(" ", "-"))

Output: Python-is-easy-to-learn

Example 3: Limit Replacements

text = "apple apple apple"
print(text.replace("apple", "mango", 2))

Output: mango mango apple

5. Splitting Strings with split()

The split() method divides a string into a list of smaller strings.

Syntax

string.split(separator, maxsplit)
  • separator: Optional delimiter used to split the string.

  • maxsplit: Optional maximum number of splits.

Example 1: Split a Sentence

text = "Python is easy"
print(text.split())

Output:

['Python', 'is', 'easy']

Example 2: Split Using a Comma

languages = "HTML,CSS,JavaScript,Python"
print(languages.split(","))

Output:

['HTML', 'CSS', 'JavaScript', 'Python']

Example 3: Limit the Number of Splits

text = "red-green-blue-yellow"
print(text.split("-", 2))

Output:

['red', 'green', 'blue-yellow']

6. Joining Strings with join()

The join() method combines strings from an iterable using a separator.

Example

languages = ["HTML", "CSS", "Python"]

result = ", ".join(languages)
print(result)

Output: HTML, CSS, Python

Joining with a Hyphen

words = ["learn", "python", "today"]
print("-".join(words))

Output: learn-python-today

Important: The items being joined must be strings. Convert non-string values before joining them.

7. Searching with find() and index()

Both methods search for a substring, but they handle missing text differently.

find()

Returns the starting index of the first occurrence or -1 if the substring is not found.

text = "Learn Python Programming"

print(text.find("Python"))
print(text.find("Java"))

Output:

6
-1

index()

Returns the starting index when the substring is found. If it is missing, Python raises a ValueError.

text = "Python Programming"
print(text.index("Programming"))

Output: 7

Difference: Use find() when you want a -1 result for missing text. Use index() when missing text should raise an error.

8. Counting Occurrences with count()

The count() method returns the number of non-overlapping occurrences of a substring.

text = "banana"

print(text.count("a"))
print(text.count("an"))

Output:

3
2

You can also count a substring within a specified range:

text = "banana"
print(text.count("a", 0, 4))

Output: 2

9. Checking String Content

Python provides methods that return True or False based on the characters in a string.

Method Purpose Example Result
isalpha() Checks alphabetic characters "Hello".isalpha() → True
isdigit() Checks digit characters "123".isdigit() → True
isalnum() Checks letters and digits "Code123".isalnum() → True
islower() Checks lowercase cased letters "hello".islower() → True
isupper() Checks uppercase cased letters "HELLO".isupper() → True
isspace() Checks whitespace characters " ".isspace() → True
istitle() Checks title-case formatting "Hello World".istitle() → True

Example

username = "Rahul123"
pin = "4567"

print(username.isalnum())
print(pin.isdigit())

Output:

True
True

Note: isdigit() accepts certain Unicode digit characters too. If an application requires ASCII digits only, use an explicit check such as value.isascii() and value.isdigit().

10. Checking the Beginning and End of Text

startswith()

Checks whether a string begins with the specified text.

filename = "report.pdf"
print(filename.startswith("report"))

Output: True

endswith()

Checks whether a string ends with the specified text.

filename = "report.pdf"
print(filename.endswith(".pdf"))

Output: True

These methods are useful for checking filename extensions, URL prefixes, and text patterns.

11. String Alignment Methods

Python provides methods to align text within a specified width.

center()

text = "Python"
print(text.center(12, "-"))

Output: ---Python---

ljust()

text = "Python"
print(text.ljust(10, "-"))

Output: Python----

rjust()

text = "Python"
print(text.rjust(10, "-"))

Output: ----Python

These methods can help format simple console reports and text-based tables.

12. Practical Project: Clean User Input

This program removes unnecessary spaces and standardizes a name and email address.

name = input("Enter your name: ").strip().title()
email = input("Enter your email: ").strip().lower()

print("Name:", name)
print("Email:", email)

Sample Input:

Enter your name:    rahul sharma
Enter your email:   RAHUL@EXAMPLE.COM

Output:

Name: Rahul Sharma
Email: rahul@example.com

This example demonstrates basic input cleaning. Real applications should also validate email addresses appropriately.

13. Practical Project: Word Counter

The following program counts words, characters, and occurrences of a selected word.

text = input("Enter a sentence: ").strip()
search_word = input("Enter a word to count: ").strip()

words = text.split()

print("Total words:", len(words))
print("Total characters:", len(text))
print("Matching occurrences:", text.lower().count(search_word.lower()))

Sample Input:

Enter a sentence: Python is easy and Python is useful
Enter a word to count: python

Output:

Total words: 7
Total characters: 36
Matching occurrences: 2

The occurrence count checks substring matches, not whole words only.

14. Common Mistakes

Mistake 1: Expecting the original string to change

text = "python"
text.upper()

print(text)

Output: python

Correct approach:

text = text.upper()
print(text)

Output: PYTHON

Mistake 2: Using an incorrect separator

text = "HTML,CSS,Python"
print(text.split("-"))

This returns a list containing the entire string because no hyphen exists.

Correct approach:

print(text.split(","))

Mistake 3: Joining numbers directly

numbers = [1, 2, 3]
print("-".join(numbers))

This raises a TypeError because the list contains integers.

Correct approach:

numbers = [1, 2, 3]
print("-".join(map(str, numbers)))

Output: 1-2-3

Mistake 4: Confusing find() and index()

find() returns -1 when text is missing, while index() raises a ValueError.

15. Practice Programs

Try writing these programs:

  1. Convert a sentence to uppercase and lowercase.

  2. Remove leading and trailing spaces from user input.

  3. Replace spaces in a sentence with underscores.

  4. Split a comma-separated list of names.

  5. Join a list of programming languages with commas.

  6. Count how many times a character appears in a word.

  7. Check whether a filename ends with .pdf.

  8. Check whether a username contains only letters and digits.

  9. Count the words in a sentence.

  10. Search for a word using find().

  11. Format a heading using center().

  12. Replace only the first two occurrences of a word.

  13. Check whether a sentence starts with a particular phrase.

  14. Create a basic input-cleaning program.

  15. Build a simple text-analysis program.

16. Quiz: Test Your Knowledge

Q1. What does upper() do?

Answer: Returns a string with cased letters converted to uppercase.

Q2. What does strip() remove by default?

Answer: Whitespace from both ends of a string.

Q3. What does split() return?

Answer: A list of strings.

Q4. What does find() return when a substring is missing?

Answer: -1.

Q5. What happens when index() cannot find a substring?

Answer: It raises a ValueError.

Q6. Which method joins a list of strings?

Answer: join().

Q7. Which method checks whether a string ends with a specified suffix?

Answer: endswith().

Q8. Do string methods normally modify the original string?

Answer: No. Strings are immutable, and methods return results.

17. Assignment

Build a Text Cleaning and Analysis Tool that:

  1. Accepts a sentence from the user.

  2. Removes leading and trailing whitespace.

  3. Displays uppercase and lowercase versions.

  4. Counts the words and characters.

  5. Replaces spaces with hyphens.

  6. Splits the sentence into a list of words.

  7. Asks the user for a word to search for.

  8. Displays the number of matching substring occurrences.

  9. Checks whether the sentence starts with a specified word.

  10. Displays all results in a clean format.

18. Summary

In this tutorial, you learned about:

  • Case conversion methods: upper(), lower(), title(), capitalize(), and swapcase().

  • Whitespace methods: strip(), lstrip(), and rstrip().

  • Text replacement with replace().

  • Splitting and joining strings with split() and join().

  • Searching with find() and index().

  • Counting with count().

  • Validation methods such as isalpha(), isdigit(), and isalnum().

  • Prefix and suffix checks with startswith() and endswith().

  • Text alignment with center(), ljust(), and rjust().

  • Practical projects, common mistakes, and practice programs.

Conclusion: Python string methods simplify text processing and help developers build useful programs for input cleaning, searching, formatting, and data analysis. Practise these methods regularly to strengthen your Python programming skills.

←
Post 8 of 20
→