Programming with Python · free preview

Working with Strings

Slice strings, clean and transform text with methods, split and join, and format values into new strings with f-strings.

1. Overview

Overview

2. Strings Are Sequences

Strings Are Sequences

3. Cleaning and Transforming Text

Cleaning and Transforming Text

4. Splitting and Joining

Splitting and Joining

5. Formatting with f-Strings

Formatting with f-Strings

6. Searching and Testing Text

Searching and Testing Text

7. Normalize a Header

Normalize a Header

8. Temperature Report

Temperature Report

9. Normalize the header fields

For header = " Name , AGE , temp ", what list does stripping and lowercasing each comma-separated field produce? Give the exact list.

10. Trace a header cleanup and a temperature report

Predict the cleaned header list and the two report lines before you run the program. Then run it and compare each printed line, including the effect of strip, lower, split, and the f-string.

Example. Trace a header cleanup and a temperature report

Problem. Predict the cleaned header list and the two report lines before you run the program. Then run it and compare each printed line, including the effect of strip, lower, split, and the f-string.

Correct solution.

python
header = " City ,POP ,avgTemp "
fields = []
for field in header.split(","):
    fields.append(field.strip().lower())
print(fields)

readings = [36.7, 37.2, -5.0]
for day, value in enumerate(readings, start=1):
 print(f"day {day}: {value:.1f}")

Output

['city', 'pop', 'avgtemp']
day 1: 36.7
day 2: 37.2
day 3: -5.0

Trace.

  • header.split(',') creates three raw fields with different leading and trailing whitespace.
  • The list comprehension applies .strip() to remove padding and .lower() to normalize case for every field.
  • enumerate(readings, start=1) supplies day numbers 1, 2, and 3; it does not modify readings.
  • The format spec :.1f keeps one decimal, and -5.0 still prints with a minus sign.

关键提醒。

Strings are immutable, so each cleanup method creates a new string. Splitting produces the field pieces, strip removes padding, lower normalizes case, and f-strings build the report. Format specs control shape only; they do not change the stored reading.

11. Retrieval practice

Given header = " Day , Temp_C , Notes ", write the split-transform-print line that converts it to ['day', 'temp_c', 'notes']. State the exact output and explain why using .replace(' ', '') on the whole header would not be enough for this case.

Answer with the list comprehension or equivalent loop and the exact printed list.

12. Mastery check

Apply string formatting to a new report input, readings = [36.65, 38.04], one decimal place, and day numbers starting at 0. Write the loop using enumerate(readings, start=0) and give the exact two printed lines.

Include the start value, the f-string, and both exact output lines.

Practice this interactively

Free account · instant grading · spaced review that schedules itself.

Start this course for free