liveBook · Manning

Trim

As explained in A Pythonic Adventure: From Python basics to a working web app

The Python string strip method returns a string with specified leading and trailing whitespace or characters removed.

When menu items come from a file, each line may carry an invisible newline character. Calling strip() removes invisible characters from both ends of each string, so a printed list becomes clean and readable. section 5.0 section 5.1

Clean Erik’s menu

Read the file into a temporary list, loop over its items, strip each item, and append the cleaned value to a new list. The result changes ['coffee\n', 'chocolate\n', 'decaf\n'] into ['coffee', 'chocolate', 'decaf']. The same helper can clean drinks, flavors, and toppings. section 5.0

f = open("drinks.txt")
temp = f.readlines()
drinks = []
for item in temp:
    new_item = item.strip()
    drinks.append(new_item)
 
print(drinks)

Shows the complete loop that applies strip() to every item and builds the cleaned drinks list. section 5.0

How A Pythonic Adventure: From Python basics to a working web app covers it

How deep it goes
Explains invisible newline characters and demonstrates applying strip() inside a readable loop, without exploring alternate forms.
Examples
Uses drinks, flavors, and toppings files whose newline-ended entries become clean menu lists.
What it assumes
Assumes basic strings, lists, loops, and file reading while teaching newline characters from the beginning.
What you can do after
Apply it via Python’s strip() method to remove newline characters from strings read from files.
How it connects
Connects string cleanup with file reading, lists, loops, functions, and returning menu data.

Also explained in

Compare how 4 books explain trim →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of A Pythonic Adventure: From Python basics to a working web app. The section links point to the parts of the book it draws on.