Working with Text · practice
Useful String Methods
In the look-under-the-hood lesson, you learned that a
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:
messagerefers to the string receiving the operation.The dot connects that string to one of its methods.
upperis the method name.The parentheses call the method.
The uppercase string is the
.
You can capture a method’s return value with 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:
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
Python handles the chained
raw_answer.strip()returns"OUTDOOR"without the surrounding spaces..lower()is called on that returned string and produces"outdoor".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
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:
clean_titleis the result of calling.strip()onraw_title;loud_titleis the result of calling.upper()onclean_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