Working with StringsBeginner8 min19 / 63

String Methods

Learn how to transform, search, and clean text using Python's built-in string methods — the everyday tools every Python programmer reaches for.

Strings are everywhere: names, messages, addresses, emails. Real-world text is messy — it has extra spaces, odd capitalization, or needs to be split apart. Python gives every string a built-in toolkit called methods. A method is like a helper function that lives on the string itself. You call it with a dot: "hello".upper(). In this lesson you will learn the most useful ones.

See it in action

Visual walkthrough1 / 6
1

Strings Have Built-In Tools

Every string in Python comes with a built-in toolkit of methods — helpers you call with a dot. They let you transform, search, and clean text without writing any complex code yourself.

A method is just a function that lives on the string: `"hello".upper()`

#Changing Case

Three methods handle capitalization. They are useful for displaying names nicely or comparing text without worrying about whether someone typed 'PYTHON' or 'python'.

upper(), lower(), and title() in action
name = "alice wonder"

print(name.upper())   # all capitals
print(name.lower())   # all lowercase
print(name.title())   # first letter of each word capitalised
Think of it like

Methods are tools on a Swiss Army knife

Think of a string as a piece of paper, and methods as the tools clipped to the side. You pick the tool you need — upper(), lower(), strip() — and it does its job, handing you back a new piece of paper with the result.

#Strings Are Immutable — Methods Return NEW Strings

This is one of the most important things to understand: calling a method does not change the original string. It always hands you back a brand-new string. You need to save that result in a variable if you want to use it.

The original string is never changed
greeting = "hello"

# This does NOT change greeting
greeting.upper()

print(greeting)  # still lowercase!

# You must capture the result
louder = greeting.upper()
print(louder)
Common mistake

Forgetting to save the result

A very common beginner mistake:

``python word = "python" word.upper() # result is thrown away! print(word) # still 'python' ``

Always assign the result: word = word.upper().

#Cleaning Up Whitespace with strip()

When users type text into a form, they often accidentally add spaces at the start or end. strip() removes those for you. lstrip() removes only from the left, and rstrip() only from the right.

strip() removes leading and trailing whitespace
user_input = "   alice@example.com   "

cleaned = user_input.strip()
print(repr(cleaned))  # repr() shows quotes so you can see spaces clearly

#Finding and Replacing Text

replace(old, new) swaps every occurrence of one piece of text with another. find(text) tells you where something appears — it returns the index (position number), or -1 if not found.

replace() is case-sensitive — 'cats' and 'Cats' are treated differently
sentence = "I love cats. Cats are great."

print(sentence.replace("cats", "dogs"))
print(sentence.replace("Cats", "Dogs"))
find() returns the starting index, or -1 if absent
text = "Python is fun"

position = text.find("fun")
print(position)   # index where 'fun' starts

missing = text.find("boring")
print(missing)    # -1 means not found

#Counting and Checking

count(text) tells you how many times something appears. startswith(text) and endswith(text) check the beginning or end of a string and return True or False. isdigit() checks whether every character is a number.

Counting and checking methods
sentence = "banana banana banana"

print(sentence.count("banana"))       # how many times?
print(sentence.startswith("banana"))  # True or False?
print(sentence.endswith("apple"))     # True or False?

code = "12345"
print(code.isdigit())  # True — all digits

#Splitting and Joining — A Power Pair

split() breaks a string into a list of pieces. join() does the reverse — it glues a list of strings back together. They work perfectly as a team for reshaping text.

split() turns a string into a list
csv_line = "Alice,Bob,Charlie,Diana"

names = csv_line.split(",")  # split on the comma
print(names)
print(type(names))
join() is called on the separator string — this trips up many beginners!
names = ["Alice", "Bob", "Charlie"]

# join() is called on the SEPARATOR, not the list
result = " | ".join(names)
print(result)
Tip

split() with no argument splits on any whitespace

" hello world ".split() returns ['hello', 'world'] — it automatically handles multiple spaces and strips them. Very handy for cleaning up messy input.

#Method Chaining

Because each method returns a new string, you can call another method immediately on that result. This is called chaining — reading left to right, each method hands its output to the next.

Chaining: strip() -> lower() -> replace()
raw = "   HELLO, world!   "

# strip, then lower, then replace — all in one line
cleaned = raw.strip().lower().replace(",", "")
print(cleaned)

#A Practical Example: Cleaning User Input

Here is how you might combine several methods to clean up a username before saving it to a database.

strip whitespace, lowercase, replace spaces with underscores
raw_username = "  Ali Khan  "

username = raw_username.strip().lower().replace(" ", "_")
print(username)
Quick check

What does this code print? ```python word = "python" word.upper() print(word) ```

Key takeaways

  • String methods are called with a dot: `text.method()` — they are built right into every string.
  • Methods never change the original string; they always return a new one. Always save the result.
  • `strip()`, `replace()`, and `lower()` are your best friends for cleaning messy text.
  • `split()` turns a string into a list; `join()` turns a list back into a string — use them as a pair.
  • You can chain methods one after another to transform text in a single readable line.
Practice challenges
Test yourself · earn XP
0/4
Predict the output#1

What does this code print?

predict-output
greeting = "hello"
greeting.upper()
print(greeting)
Fix the bug#2

This code should print 'alice@example.com' (all lowercase, no extra spaces), but it doesn't work as expected. What is wrong?

fix-bug
email = "  Alice@Example.COM  "
email.strip()
email.lower()
print(email)
Fill in the blank#3

Complete the code so it prints 'PYTHON IS FUN'.

text = "python is fun"
print(text.())
Reorder the lines#4

Put these lines in the right order so the code splits the sentence into words and prints them joined by a dash, like: 'I-love-Python'.

1
result = "-".join(words)
2
sentence = "I love Python"
3
words = sentence.split()
4
print(result)
Your turn
Practice exercise

You have received a messy list of email addresses as a single string: " Alice@Example.COM , bob@GMAIL.COM, CHARLIE@outlook.com ". Your task: split it on the comma, then clean each email by stripping whitespace and converting to lowercase. Print each cleaned email on its own line.

Try it live — edit the code and hit Run to execute real Python:

solution.py · editable