Skip to content

String Methods

String (str) methods allow you to manipulate and analyze text efficiently. They are essential in tasks such as file processing, user input, report generation, and in general, any system that works with textual data. Thanks to their simplicity and expressiveness, these methods are a key tool in cleaning, transforming, and searching for textual information.

FunctionDescription
.lower()Converts all characters to lowercase.
.upper()Converts all characters to uppercase.
.capitalize()Converts the first character to uppercase and the rest to lowercase.
.title()Converts the first letter of each word to uppercase.
.strip()Removes whitespace at the beginning and end of a string.
.replace()Replaces one substring with another.
.split()Divides the string into a list according to a separator.
.join()Joins elements of a sequence using the string as a separator.
.find()Returns the position of the first occurrence of a substring, or -1 if it does not exist.
.startswith()Returns True if the string starts with a given substring.
.endswith()Returns True if the string ends with a given substring.

Below I will explain in more detail how these functions work:

Typical use: Convert a string to lowercase.

lower.py
text = 'Hello World'
print(text.lower())

Output:

lower.py
hello world

Typical use: Convert a string to uppercase.

upper.py
text = 'Hello World'
print(text.upper())

Output:

upper.py
HELLO WORLD

Typical use: Capitalize only the first letter and lowercase the rest.

capitalize.py
text = 'hello WORLD'
print(text.capitalize())

Output:

capitalize.py
Hello world

Typical use: Convert the first letter of each word to uppercase.

title.py
text = 'hello world from PyDocs'
print(text.title())

Output:

title.py
Hello World From Pydocs

Typical use: Remove whitespace at the beginning and end.

strip.py
text = ' hello world '
print(text.strip())

Output:

strip.py
hello world

Typical use: Replace one substring with another.

replace.py
text = 'I like Python'
print(text.replace('Python', 'JavaScript'))

Output:

replace.py
I like JavaScript

Typical use: Split a string into a list.

split.py
text = 'red,green,blue'
print(text.split(','))

Output:

split.py
['red', 'green', 'blue']

Typical use: Join elements of a list with a separator.

join.py
colors = ['red', 'green', 'blue']
print(', '.join(colors))

Output:

join.py
red, green, blue

Typical use: Find the position of a substring.

find.py
text = 'search in this phrase'
print(text.find('this'))

Output:

find.py
10

Typical use: Verify if the string starts with a substring.

startswith.py
file = 'image.png'
print(file.startswith('image'))

Output:

startswith.py
True

Typical use: Verify if the string ends with a substring.

endswith.py
file = 'image.png'
print(file.endswith('.png'))

Output:

endswith.py
True