Methods

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — Introduction to String Methods

In Python, strings come with built-in methods that help you work with text. These methods are special functions that belong to string objects and can help you transform and analyze text.

You call a string method using the dot notation after a string: string_variable.method_name()

Important Note

String methods don't change the original string. They return a new string with the changes applied. This is because strings in Python are immutable (cannot be changed after creation).

Exercise 2 — Changing Case with upper() and lower()

The upper() and lower() methods are used to convert strings to uppercase or lowercase letters.

# Examples with upper() and lower() codemon_type = "Water" # Convert to uppercase upper_case = codemon_type.upper() print("Uppercase:", upper_case) # Convert to lowercase lower_case = codemon_type.lower() print("Lowercase:", lower_case)

Changing case??

Case for strings refers to whether letters are uppercase (A-Z) or lowercase (a-z). "Aquachu" and "aquachu" are the same word, but they have different cases.

Exercise 3 — Understanding upper() and lower()

Consider the following code:

name = "Florachu" upper_name = name.upper() print(upper_name)

What will be printed?

Options
• FLORACHU
• Florachu
• florachu
• An error message

Hint : The upper() method converts all characters in the string to uppercase and returns the new string.

Exercise 4 — Removing Whitespace with strip()

The strip() method removes whitespace (spaces, tabs, newlines) from the beginning and end of a string.

# String with extra spaces text_with_spaces = " Pyrochu " print("Original: " + text_with_spaces + ".") # Remove spaces with strip() clean_text = text_with_spaces.strip() print("After strip(): " + clean_text + ".")

The strip() method is especially useful when cleaning user input or processing data from external sources.

Note about strip()

The strip() method only removes whitespace from the beginning and end of a string, not from within the string.

Exercise 5 — Using strip() Correctly

Complete the code to clean up the Codémon name by removing extra spaces using the correct string method.

Hint : The method that removes whitespace from the beginning and end of a string is a common cleaning operation in text processing.

Exercise 6 — Checking Substrings with the 'in' Operator

The in operator checks if a substring exists within another string. It returns True if the substring is found, and False otherwise.

Unlike upper(), lower(), and strip(), in is not a method but an operator, so the syntax is different.

codemon_name = "Aquachu" # Check if 'Aqua' is in the name print("Aqua" in codemon_name) # Check if 'aqua' is in the name print("aqua" in codemon_name) # NOT found, case-sensitive, Aqua != aqua

The in operator is case-sensitive. If you need to do a case-insensitive check, you can convert both strings to the same case first.

Exercise 7 — Using the 'in' Operator

What will the following code print?

codemon_types = "WaterFireGrass" print("fire" in codemon_types)
Options
• False
• True
• Error
• None

Hint : Remember: The 'in' operator is case-sensitive. Pay attention to uppercase and lowercase letters in the strings being compared.

Exercise 8 — Replacing Text with replace()

The replace() method allows you to replace occurrences of a substring with another string.

Syntax: string.replace(old, new, count) - old: the substring to replace - new: the string to replace it with - count (optional): maximum number of replacements to make

# Basic replace() example sentence = "I choose Aquachu! Aquachu is a water type." # Replace all occurrences of Aquachu with Pyrochu new_sentence = sentence.replace("Aquachu", "Pyrochu") print(new_sentence) # Replace only the first occurrence first_only = sentence.replace("Aquachu", "Pyrochu", 1) print(first_only)

replace() Behavior

By default, replace() replaces all occurrences of the substring. If you want to limit the number of replacements, use the optional count parameter. Like other string methods, replace() returns a new string and doesn't modify the original.

Exercise 9 — Using the replace() Method

Complete the code to replace 'Fire' with 'Water' in the description of a Codémon.

Hint : The replace() method takes at least two arguments: the substring to find and the string to replace it with.

Exercise 10 — Match String Methods with Their Purpose

Match each string method or operator with its correct purpose.

Items to match
• upper()
• lower()
• strip()
• in
• replace()
Definitions
• Converts all characters to uppercase
• Converts all characters to lowercase
• Removes whitespace from beginning and end
• Checks if a substring exists in a string
• Replaces occurrences of a substring with another string

Exercise 11 — Match Code with Output

Match each code snippet with its correct output.

Items to match
• "Aquachu".upper()
• " Flora ".strip()
• "chu" in "Pyrochu"
• "A".replace("A", "B")
Definitions
• AQUACHU
• Flora
• True
• B

Exercise 12 — Codémon Battle Message Formatter

Create a message formatter for Codémon battles! You receive a battle announcement with some mistakes that need fixing. Write a program that: - Removes extra whitespace from the beginning and end and stores it in a variable - Converts the message to uppercase and stores it in a variable - Fixes the mistake: it's not Aquachu but Pyrochu, replace it and store it in a variable - Prints the cleaned and formatted message

Starter code
messy_message = " Aquachu enters the battle arena! " # Clean and format the message here
Back to the course