How do I trim whitespace?
In Python, you can use the .strip()
method to remove leading and trailing whitespace from a string. Here is an example:
string_with_whitespace = " This string has leading and trailing whitespace. "
trimmed_string = string_with_whitespace.strip()
print(trimmed_string)
# Output: "This string has leading and trailing whitespace."
Watch a video course
Python - The Practical Guide
If you want to remove only leading or trailing whitespace, you can use the .lstrip()
or .rstrip()
methods respectively:
string_with_whitespace = " This string has leading whitespace. "
trimmed_string = string_with_whitespace.lstrip()
print(trimmed_string)
# Output: "This string has leading whitespace. "
string_with_whitespace = " This string has trailing whitespace. "
trimmed_string = string_with_whitespace.rstrip()
print(trimmed_string)
# Output: " This string has trailing whitespace."
You can also pass in specific characters you want to remove
string_with_custom_chars = "###This string has ### custom chars###"
trimmed_string = string_with_custom_chars.strip("#")
print(trimmed_string)
# Output: "This string has ### custom chars"