livepython.net
CHAPTER 12Working With Strings
12.2  METHODS

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.

PYTHONedit me
name = "sunny kumar"
print(name.upper())
print(name.title())
print(name.capitalize())
print("HELLO".lower())
OUTPUT
SUNNY KUMAR
Sunny Kumar
Sunny kumar
hello
MethodWhat 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

PYTHONedit me
name = "rocky"
name.upper()
print(name)
OUTPUT
rocky

No error, but nothing changed! name.upper() made "ROCKY", and nobody stored it.

Good: store the new string

PYTHONedit me
name = "rocky"
name = name.upper()
print(name)
OUTPUT
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.

your turnPredict the output

What will this print?

city = "pune" city.upper() print(city)
Your turn! What will this code show on the screen?
your turnType the output

Type what this prints

print("lucky singh".title())
Read the code line by line, then type the output exactly.

Remove Extra Spaces with strip()

The strip() method removes spaces from both ends of a string. Spaces in the middle stay. It also removes tabs and new lines at the ends.

Think of it like trimming the crust off a slice of bread: the edges go, the middle stays.

PYTHONedit me
text = "   Sunny   "
print("[" + text + "]")
print("[" + text.strip() + "]")
print("[" + text.lstrip() + "]")
print("[" + text.rstrip() + "]")
OUTPUT
[   Sunny   ]
[Sunny]
[Sunny   ]
[   Sunny]

The square brackets are only there so you can see the spaces.

The rules

MethodRemoves spaces from
strip()both ends
lstrip()the left end only
rstrip()the right end only
  • The middle is never touched: "Sunny Kumar".strip() keeps both spaces.
  • Put characters in the brackets to strip those instead: "**hi**".strip("*") gives "hi".

Chain methods to clean up answers

In chapter 8, "Yes" with a capital Y, or with a space, didn't match "yes". Now you can fix that. Chain two methods: each one works on the result of the one before, from left to right.

PYTHONedit me
answer = input()
if answer.strip().lower() == "yes":
    print("Great, let's start!")
else:
    print("Maybe later.")
OUTPUT
Great, let's start!

" YES" becomes "YES" after strip(), then "yes" after lower(), and the comparison is True.

Common beginner doubt: "Should I always strip user input?" For text answers, yes: people often type a space by accident. For int(input()) you don't need to, because int() ignores spaces at the ends by itself.

strip() trims the ends, and strip().lower() makes user answers easy to compare.

your turnFill the gap

Make the messy answer match

answer = " Yes " if answer.? == "yes": print("OK") else: print("No")

It should print: OK

Which piece makes this code work?
your turnPredict the output

Remember what input() gives you?

age = input() print(age + "1")

The user types: 20

Your turn! What will this code show on the screen?

Replace Text with replace()

The replace() method swaps one piece of text for another: text.replace(old, new). It returns a new string with every old changed to new.

Think of it like "Find and replace" in a word processor: type what to find, type what to put instead, and every match changes at once.

PYTHONedit me
msg = "I like cats. cats are cute."
print(msg.replace("cats", "dogs"))
OUTPUT
I like dogs. dogs are cute.

Remove text

Replace something with an empty string "", and it disappears:

PYTHONedit me
phone = "98-765-43210"
print(phone.replace("-", ""))
print("Sunny  Kumar".replace("  ", " "))
OUTPUT
9876543210
Sunny Kumar

The second line fixes the double space in the middle that strip() couldn't touch.

The rules

  • It replaces every match, not only the first.
  • It's case-sensitive: "Cats" won't match "cats".
  • If nothing matches, you get the same text back. No error.
  • A third value limits how many to replace: "a-b-c".replace("-", " ", 1) gives "a b-c".
  • Like every string method, it returns a new string. Store it to keep it.

Avoid: the wrong capitals

PYTHONedit me
greeting = "Hello World"
print(greeting.replace("world", "Sunny"))
OUTPUT
Hello World

Nothing changed, and there's no error to warn you: "world" with a small w isn't in the text. Copy the exact capitals.

Common beginner doubt: "Can I replace several different things?" Yes, chain them: text.replace("-", "").replace(" ", "") removes the dashes, then the spaces.

text.replace(old, new) swaps every match and returns a new string.

your turnPredict the output

What will this print?

print("banana".replace("a", "o"))
Your turn! What will this code show on the screen?
your turnFix the code

Fix the code so it prints: 2024-01-15

It should print: 2024-01-15

date = "2024/01/15"
date.replace("/", "-")
print(date)
This code does not work yet. Fix it, then press Run.

Search a String: find(), count() and startswith()

Four methods search a string for you. find() says where a piece is, count() says how many times it appears, and startswith() and endswith() say yes or no.

Think of it like pressing Ctrl+F on a web page: the browser shows where the word is and how many matches there are.

PYTHONedit me
email = "sunny@example.com"
print(email.find("@"))
print(email.count("m"))
print(email.endswith(".com"))
print(email.startswith("rocky"))
OUTPUT
5
2
True
False

The rules

You writeYou get
text.find("x")the index of the first "x", or -1 if it isn't there
text.count("x")how many times "x" appears
text.startswith("x")True if the text begins with "x"
text.endswith("x")True if the text ends with "x"
"x" in textTrue if "x" is anywhere (topic 1)

All of them are case-sensitive.

find() and slicing together

find() gives an index, and an index is exactly what a slice needs. Here's how to cut the name out of an email address:

PYTHONedit me
email = "sunny@example.com"
at = email.find("@")
print(email[:at])
print(email[at + 1:])
OUTPUT
sunny
example.com

Avoid: using -1 as an index by mistake

When find() finds nothing, it gives -1, not an error. But -1 is also a real index: the last character!

PYTHONedit me
name = "Sunny"
pos = name.find("z")
print(pos)
print(name[pos])
OUTPUT
-1
y

No error, but a wrong answer. Check first: if pos != -1:, then use it.

Common beginner doubt: "find() or in?" Use in when you only need yes or no. Use find() when you need the position.

find() says where, count() says how many, startswith() and endswith() say yes or no.

your turnType the output

Type what this prints

print("mississippi".count("ss"))
Read the code line by line, then type the output exactly.
your turnPick the right idea

What does "Rocky".find("x") give?

Think about it, then pick one.

Check Text with isdigit() and isalpha()

isdigit() gives True when every character of a string is a digit from 0 to 9. isalpha() gives True when every character is a letter. They let you check text before you use it.

Think of it like a ticket checker at a gate: the ticket is looked at first, and only a good one gets through.

The rules

  • isdigit() is False for "-5" and "3.5": the minus sign and the point aren't digits.
  • An empty string "" is False for both.
  • isalpha() is False as soon as there's a space or a digit.
  • Like startswith(), these give True or False, so they fit straight into an if.
PYTHONedit me
print("2024".isdigit())
print("-5".isdigit())
print("3.5".isdigit())
print("".isdigit())
print("Sunny".isalpha())
print("Sunny 1".isalpha())
OUTPUT
True
False
False
False
True
False

Avoid: int() on text that isn't a number

PYTHONedit me
age = int(input())
print(age + 1)
OUTPUT
ValueError: invalid literal for int() with base 10: 'twenty'

You met this error in chapter 7. int() can't turn "twenty" into a number, so the program crashes.

Good: check first, then convert

PYTHONedit me
text = input()
if text.isdigit():
    age = int(text)
    print("Next year you will be", age + 1)
else:
    print("Please type a number.")
OUTPUT
Please type a number.

Type 20 in the Input box and run it again: now the number is used.

Common beginner doubt: "What about negative numbers and decimals?" isdigit() is perfect for whole numbers like ages and quantities. For any kind of bad input, there's a stronger tool called try and except. You'll learn it in chapter 17.

Check text with isdigit() before you turn it into an int.

your turnPredict the output

What will this print?

print("12.5".isdigit())
Your turn! What will this code show on the screen?
your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.

Practice: Methods

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 102.Python Program to Clean Up a Name with strip() and title()EasySolve
  2. 103.Python Program to Count the Vowels in a SentenceMediumSolve
  3. 104.Python Program to Check a Simple Email AddressMediumSolve