You can remove all whitespace (including spaces, tabs, and newline characters) from the start and end of a string in Python using the str.strip()
method. Here's an example:
python
# Input string with leading and trailing whitespace
text = " This is a sample string with whitespace. \n"
# Remove whitespace from the start and end of the string
trimmed_text = text.strip()
# Print the trimmed string
print("Original String:")
print(text)
print("Trimmed String:")
print(trimmed_text)
In this example:
We have an input string
text
that contains leading and trailing whitespace, including spaces and a newline character.We use the
strip()
method on thetext
string to remove all leading and trailing whitespace.The result is stored in the
trimmed_text
variable.We then print both the original string and the trimmed string.
The strip()
method trims all leading and trailing whitespace by default. If you want to remove only leading or trailing whitespace, you can use lstrip()
to remove leading whitespace or rstrip()
to remove trailing whitespace specifically.
Comments
Post a Comment