More String Methods: case, strip, and startswith
Three more groups of string methods you'll need constantly: case methods (.lower(), .upper(), .title()) for normalizing text, .strip() for trimming whitespace or other characters from the edges, and .startswith() / .endswith() for prefix and suffix checks.
Three more groups of string methods worth knowing: case methods, .strip(), and .startswith() / .endswith().
Let's start with case. .lower() returns a new string with every letter in lowercase:
.upper() is the opposite. It returns the string in all caps:
Two more case helpers: .title() capitalizes the first letter of every word, and .capitalize() only capitalizes the very first letter of the string.
See the difference on the same input:
What will be the output?
Like every string method, these return a new string. The original variable is never changed unless you reassign it.
What will be the output?
Next up: .strip(). It removes characters from both ends of a string. By default, it strips whitespace.
Notice the spaces are gone from both sides, but the space in the middle stays:
Pass any string of characters to strip those instead. Here we trim hash signs from both ends:
If you only want to trim one side, use .lstrip() for the left or .rstrip() for the right.
Right-strip removes only the trailing characters:
What will be the output?
Finally, two methods that ask a yes-or-no question about a string: .startswith() and .endswith(). Both return a boolean.
Check whether a URL begins with a known prefix:
Both methods accept a tuple to check several options at once. Handy for file extensions:
What will be the output?
What will be the output?
What will be the output?