String methods
🌍 In real life. At a photocopy shop, you hand over a page and ask for it "in bigger letters". You get back a new copy made bigger; your original page is exactly as it was. If you want the bigger one, you have to keep the copy.
String methods work like that shop: they hand you a new string and never touch the original.
The idea in one sentence: a method is a function that belongs to a value, called with a dot, and a string method always gives back a new string instead of changing the old one.
Its words:
- method: a function attached to a value, like
upperon a string - the dot:
text.upper()means "the upper method of text" - gives back (returns): the new value a method hands you
- chaining: calling a method on the result of another,
text.strip().lower()
Step by step, for "hello".upper():
- Python takes the value
"hello". - It finds that string's
uppermethod and runs it. - Out comes a new string,
"HELLO";"hello"itself is unchanged.
text = "Hello World"
print(text.upper())
print(text.lower())
print(text)Why a new string? Strings can't be changed in place (Lesson 4.2), so a method can't edit the old one; it builds a new one. That's why you keep the result by putting it in a variable: text = text.upper(). Calling text.upper() on a line by itself makes the new string and then throws it away.
Methods for cleaning and changing text:
.strip()removes spaces from both ends.replace(old, new)swaps everyoldfornew.title()starts each word with a capital letter
messy = " rimi "
print(messy.strip())
print("I like tea".replace("tea", "coffee"))
print("dhaka city".title())Methods that answer questions about a string:
.startswith(x)and.endswith(x)giveTrueorFalse.find(x)gives the index wherexfirst appears, or-1if it isn't there.count(x)counts how many timesxappears
email = "rimi@mail.com"
print(email.endswith(".com"))
print(email.find("@"))
print("banana".count("a")).split() cuts a string into a list of words. (Lists get their own chapter, Chapter 8.) Add [-1] to pick the last word.
sentence = "I love Python"
print(sentence.split())
print(sentence.split()[-1])You can chain methods: each one works on the result of the one before it.
print(" Hello ".strip().lower())Asking what a string holds. Methods whose names start with is answer True or False about the whole string: isdigit() (only digits), isalpha() (only letters), isalnum() (only letters and digits), isspace() (only spaces, tabs and new lines), isupper() and islower() (it has letters, and they are all capitals, or all small). An empty string gives False. Careful: a minus sign or a decimal point isn't a digit, so "-5".isdigit() is False. Bengali digits count as digits too: "২০২৬".isdigit() is True. Chapter 5 uses these checks on what a user types.
print("2026".isdigit(), "20.5".isdigit(), "-5".isdigit())
print("Dhaka".isalpha(), "Dhaka 1".isalpha())
print("".isdigit())
print("২০২৬".isdigit(), "A1".isupper())Mistakes and edge cases.
- Not keeping the result.
name.upper()alone changes nothing; writename = name.upper(). - Forgetting the brackets.
print(text.upper)shows something like<built-in method upper of str object at 0x...>: the method itself, not its result. - A method name that doesn't exist.
"hi".uppercase()givesAttributeError: 'str' object has no attribute 'uppercase'. - find() doesn't fail. When the text isn't there,
.find()gives-1instead of an error, and-1is also a valid index, so check for it. - Capital letters matter.
"Hello".startswith("h")isFalse. - replace() changes every match, not just the first one.
Quiz
What does this print?
print("abc".upper())What does this print?
print(" hi ".strip())What does this print?
print("banana".replace("a", "o"))What does this print?
print("python".find("t"))After
s = "cat"and thens.upper(), what doesshold?- "cat"
- "CAT"
- Nothing: it's an error
This should print RIMI, but it prints rimi. Which line needs fixing?
name = "rimi" name.upper() print(name)
Coding tasks
shoutholds"hello". Makeloudhold"HELLO!": the capital-letter version with"!"added.ipholds"192.168.0.1". Makedefangedhold the IP with every.replaced by[.].rawholds" Python Rocks ". Print it without the spaces at the ends, in small letters:python rocks