How do I trim whitespace?
In Python, you can use the .strip() method to remove leading and trailing whitespace from a string.
In Python, you can use the .strip() method to remove leading and trailing whitespace from a string. Here is an example:
Trim whitespace in Python using strip method
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."
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
If you want to remove only leading or trailing whitespace, you can use the .lstrip() or .rstrip() methods respectively:
Remove only leading or trailing whitespace in Python
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
Remove specific characters from the beginning and the end of a string in Python
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"