Exerpad
🔥1
10 XP
Lv.1 Beginner
Log In

What Are String Methods?

You already know how to create strings and combine them. But strings can do so much more! Python gives you string methods — built-in tools that let you transform, search, and slice text.

To use a method, put a dot . after a string (or a variable holding a string), then the method name with parentheses:

python
message = "hello"
print(message.upper())
text
HELLO

Changing Case

Use .upper() and .lower() to change all letters to uppercase or lowercase:

python
name = "Alice"
print(name.upper())
print(name.lower())
text
ALICE
alice

Use .title() to capitalize the first letter of every word:

python
book = "the great gatsby"
print(book.title())
text
The Great Gatsby

Cleaning Up Strings

Use .strip() to remove extra spaces (or other characters) from the beginning and end:

python
messy = " hello "
print(messy.strip())
text
hello

There's also .lstrip() (left only) and .rstrip() (right only).

Replacing Text

Use .replace(old, new) to swap parts of a string:

python
sentence = "I like cats"
print(sentence.replace("cats", "dogs"))
text
I like dogs

Splitting and Joining

.split() breaks a string into a list of words:

python
sentence = "one two three"
words = sentence.split()
print(words)
text
['one', 'two', 'three']

You can split on any character:

python
data = "red,green,blue"
colors = data.split(",")
print(colors)
text
['red', 'green', 'blue']

.join() does the opposite — it glues a list into one string:

python
words = ["hello", "world"]
result = " ".join(words)
print(result)
text
hello world

Searching in Strings

Use .find() to get the position of text inside a string. It returns -1 if not found:

python
message = "hello world"
print(message.find("world"))
print(message.find("python"))
text
6
-1

Use .count() to count how many times something appears:

python
text = "banana"
print(text.count("a"))
text
3

Checking Start and End

.startswith() and .endswith() return True or False:

python
filename = "photo.png"
print(filename.endswith(".png"))
print(filename.startswith("doc"))
text
True
False

The in Operator

Use in to check if a string contains another string:

python
sentence = "I love Python"
print("Python" in sentence)
print("Java" in sentence)
text
True
False

String Slicing

You can grab parts of a string using square brackets with [start:end]:

python
word = "Python"
print(word[0:3])
print(word[2:])
print(word[:4])
text
Pyt
thon
Pyth

Use [::-1] to reverse a string:

python
word = "hello"
print(word[::-1])
text
olleh

Chaining Methods

You can chain methods together — each one works on the result of the previous one:

python
messy = " Hello World "
clean = messy.strip().lower().replace(" ", "-")
print(clean)
text
hello-world