liveBook · Manning

Trim

As explained in The Quick Python Book, Fourth Edition

strip is a Python string method that returns a copy of a string with specified characters removed from both ends, defaulting to whitespace.

Python’s strip() returns a new string with whitespace removed from both ends. It leaves internal whitespace unchanged; use lstrip() or rstrip() when only one side should change. section 6.4.3

Use the optional character argument carefully:

  • strip(chars) removes any characters listed in chars from either end, repeatedly, rather than removing one exact substring. section 6.4.3
  • Use rstrip() to remove trailing newlines from lines read from files; use removeprefix() or removesuffix() for exact matches. section 6.4.3
  • In pandas, apply .str.strip("%") to a column before converting the cleaned strings to numbers. section 24.3.2

Whitespace and character sets

x = " Hello, World\t\t " x.strip() # 'Hello, World' x.lstrip() # 'Hello, World\t\t ' x.rstrip() # ' Hello, World' x = "www.python.org" x.strip(".gorw") # 'python' x.removeprefix("www.") # 'python.org'

temp[17] = pd.to_numeric(temp[17].str.strip("%")).div(100)

Chain column cleanup, numeric conversion, and division when transforming percentage strings into fractions. section 24.3.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines edge-removal rules, directional variants, character options, exact-match alternatives, and practical examples without implementation internals.
Examples
Uses whitespace-padded strings, a website string, file-line newlines, and percentage columns in a pandas data frame.
What it assumes
Assumes familiarity with Python strings and pandas columns while demonstrating the cleanup and conversion workflow directly.
What you can do after
Apply it via Python or pandas to clean string edges and prepare values for later parsing or numeric conversion.
How it connects
Connects strip with lstrip, rstrip, removeprefix, removesuffix, replace, numeric conversion, and pandas string operations.

Also explained in

Compare how 4 books explain trim →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.