Is there a Python function that will trim whitespace (spaces and tabs) from a string?
Example: \t example string\t
→ example string
Is there a Python function that will trim whitespace (spaces and tabs) from a string?
Example: \t example string\t
→ example string
Python
trim
method is calledstrip
:This will remove all the unwanted spaces and newline characters. Hope this help
This will result :
' a b \n c ' will be changed to 'a b c'
This will remove all whitespace and newlines from both the beginning and end of a string:
If using Python 3: In your print statement, finish with sep="". That will separate out all of the spaces.
EXAMPLE:
This will print: I love potatoes.
Instead of: I love potatoes .
In your case, since you would be trying to get ride of the \t, do sep="\t"
Whitespace includes space, tabs and CRLF. So an elegant and one-liner string function we can use is translate.
' hello apple'.translate(None, ' \n\t\r')
OR if you want to be thorough
output: please_remove_all_whitespaces