Removing Leading and Trailing Whitespace with the strip() Function
The strip()
function removes whitespace (spaces, tabs, etc.) from both ends 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, thus normalizing the value.
Removing Specific Characters
By providing an argument to the strip()
function, you can remove specific characters from both ends of a string.
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.