Strings II

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:

Python
Output

.upper() is the opposite. It returns the string in all caps:

Python
Output

Two more case helpers: .title() capitalizes the first letter of every word, and .capitalize() only capitalizes the very first letter of the string.

Python

See the difference on the same input:

Python
Output

What will be the output?

Python

Like every string method, these return a new string. The original variable is never changed unless you reassign it.


What will be the output?

Python

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:

Python
Output

Pass any string of characters to strip those instead. Here we trim hash signs from both ends:

Python
Output

If you only want to trim one side, use .lstrip() for the left or .rstrip() for the right.

Python

Right-strip removes only the trailing characters:

Python
Output

What will be the output?

Python

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:

Python
Output

Both methods accept a tuple to check several options at once. Handy for file extensions:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python