0%

Working with Text · practice

Useful String Methods

In the look-under-the-hood lesson, you learned that a is a belonging to an . objects provide many methods, and a small group handles a large share of everyday text cleanup.

message = "Hello"
loud_message = message.upper()
print(loud_message)

The output is HELLO.

A method is called on a value

The call message.upper() has familiar pieces:

  • message refers to the string receiving the operation.

  • The dot connects that string to one of its methods.

  • upper is the method name.

  • The parentheses call the method.

  • The uppercase string is the .

You can capture a method’s return value with , just like the return value from input(), type(), or len().

Change letter case

.upper() returns an uppercase version:

print("Python Land".upper())

.lower() returns a lowercase version:

print("Python Land".lower())

These methods affect letters. Spaces, digits, and ordinary punctuation remain in place.

Remove surrounding whitespace

.strip() removes whitespace, such as spaces, tabs, and newlines, from the beginning and end of a string:

Try it

The square brackets make the surrounding spaces visible in the output.

.strip() does not remove spaces in the middle of text. "Python Land".strip() remains "Python Land".

This method is especially helpful with user input copied from somewhere else or entered with accidental spaces.

Chain methods when one result feeds the next

The methods in this lesson return strings, so you can call another string method on each returned . This is called method chaining.

Try it

Python handles the chained in steps:

  1. raw_answer.strip() returns "OUTDOOR" without the surrounding spaces.

  2. .lower() is called on that returned string and produces "outdoor".

  3. The final string is assigned to clean_answer.

Chaining is useful when each step is short and the combined expression remains easy to read. Use separate when you need to inspect or reuse an intermediate value.

What will this program print?

raw = "  Hello  "
print(raw.strip().upper())

Clean and capitalize a title

The starter value contains spaces at both ends.

Replace the placeholders so:

  1. clean_title is the result of calling .strip() on raw_title;

  2. loud_title is the result of calling .upper() on clean_title.

The output must be:

[Python Land]
PYTHON LAND

Keep raw_title unchanged. Store each returned string in the variable that describes it.

Task

Use .strip() to create clean_title, then use .upper() on clean_title to create loud_title.

Produce:

[Python Land]
PYTHON LAND