To trim whitespace from a string in Python, you can use the str.strip()
method. This method removes leading and trailing whitespace (including spaces, tabs, and newline characters) from the string. 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 whitespace, you can use lstrip()
. If you want to remove only trailing whitespace, you can use rstrip()
.
Comments
Post a Comment