Removing Leading and Trailing Whitespace with the strip() Function
The strip()
function removes whitespace (such as spaces and tabs) from both the beginning and end of a string.
Example of using the strip() function
text = " Hello, nice to meet you! "
stripped_text = text.strip()
print(stripped_text) # "Hello, nice to meet you!"
This function is commonly used to clean up user input by removing unnecessary spaces and normalizing the text.
Removing Specific Characters
You can also remove specific characters from both ends of a string by passing them as an argument to the strip()
function.
Example of removing specific characters
text = "xxxHello, nice to meet you!xxx"
stripped_text = text.strip('x')
# "Hello, nice to meet you!"
print(stripped_text)
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.