Python String Methods: upper, strip, replace, find
What Is a String Method? upper(), lower() and title()
A method is a tool that belongs to a value. You call it with a dot: the value, a dot, the method name and brackets, like name.upper(). Strings come with dozens of methods.
Think of it like the buttons on a TV remote. The string is the TV, and .upper() is the button you press to make it do something.
name = "sunny kumar"
print(name.upper())
print(name.title())
print(name.capitalize())
print("HELLO".lower())SUNNY KUMAR Sunny Kumar Sunny kumar hello
| Method | What you get |
|---|---|
upper() | every letter in capitals |
lower() | every letter small |
title() | the first letter of every word in capitals |
capitalize() | only the very first letter in capitals |
You already used methods on lists in chapter 9, like nums.append(5). Same dot, same brackets.
The rules
- Write the brackets, even when they're empty:
name.upper(). - A string method returns a new string. The original never changes, because strings are immutable.
- To keep the result, store it:
name = name.upper().
Avoid: calling a method and throwing the result away
name = "rocky"
name.upper()
print(name)rocky
No error, but nothing changed! name.upper() made "ROCKY", and nobody stored it.
Good: store the new string
name = "rocky"
name = name.upper()
print(name)ROCKY
Common beginner doubt: "Why did list.append() change the list, but upper() doesn't change the string?" Lists can change, so their methods change them in place. Strings can't change, so their methods always hand you a new string instead.
A string method returns a new string. Store it if you want to keep it.