Chapter 13 of 20

String Methods in Python

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 PYTHON

lower()

Converts all letters to lowercase.

text = "HELLO PYTHON"

print(text.lower())

Output:

hello python

title()

Capitalizes the first letter of each word.

text = "hello python world"

print(text.title())

Output:

Hello Python World

capitalize()

Capitalizes only the first character of the string.

text = "hello python"

print(text.capitalize())

Output:

Hello python

Removing Extra Spaces

strip()

Removes whitespace from both ends of a string.

text = "   Hello Python   "

print(text.strip())

Output:

Hello Python

There are also:

text.lstrip()   # Removes from the left
text.rstrip()   # Removes from the right

These 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:

14

If 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:

2

Checking 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:

True

endswith()

Checks whether a string ends with specific text.

filename = "report.pdf"

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

Output:

True

isdigit()

Checks whether all characters are digits.

value = "12345"

print(value.isdigit())

Output:

True

isalpha()

Checks whether all characters are alphabetic.

name = "John"

print(name.isalpha())

Output:

True

Replacing 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 Python

This 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, Mango

The 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:

6

A 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:

   JOHN123

strip() removes the extra spaces and lower() converts it to lowercase.

So the username becomes:

john123

Common String Methods

Here's a handy list of the methods you'll use most often:

Method

Purpose

upper()

Converts to uppercase

lower()

Converts to lowercase

title()

Capitalizes each word

capitalize()

Capitalizes the first character

strip()

Removes surrounding whitespace

find()

Finds the position of text

count()

Counts occurrences

replace()

Replaces text

split()

Splits a string into a list

join()

Combines strings

startswith()

Checks the beginning

endswith()

Checks the ending

isdigit()

Checks for digits

isalpha()

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.