👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!
I need to remove whitespaces after the word in the string. Can this be done in one line of code?
string = " xyz " desired result : " xyz"
👻 Read also: what is the best laptop for engineering students?
How do I trim whitespace from a string?
How do I remove leading and trailing whitespace from a string in Python?
" Hello " --> "Hello" " Hello" --> "Hello" "Hello " --> "Hello" "Bob has a cat" --> "Bob has a cat"
Just one space or all consecutive spaces? If the second, then strings already have a
>>> " Hello ".strip() "Hello" >>> " Hello".strip() "Hello" >>> "Bob has a cat".strip() "Bob has a cat" >>> " Hello ".strip() # ALL consecutive spaces at both ends removed "Hello"
If you only need to remove one space however, you could do it with:
def strip_one_space(s): if s.endswith(" "): s = s[:-1] if s.startswith(" "): s = s[1:] return s >>> strip_one_space(" Hello ") " Hello"
Also, note that
str.strip() removes other whitespace characters as well (e.g. tabs and newlines). To remove only spaces, you can specify the character to remove as an argument to
>>> " Hello ".strip(" ") "Hello "
As pointed out in answers above
will remove all the leading and trailing whitespace characters such as
For more flexibility use the following
- Removes only leading whitespace chars:
- Removes only trailing whitespace chars:
- Removes specific whitespace chars:
my_string.rstrip(" ")and so on.
More details are available in the docs.
How do I trim whitespace?
Is there a Python function that will trim whitespace (spaces and tabs) from a string?
example string ‚Üí
For whitespace on both sides use
s = " a string example " s = s.strip()
For whitespace on the right side use
s = s.rstrip()
For whitespace on the left side
s = s.lstrip()
As thedz points out, you can provide an argument to strip arbitrary characters to any of these functions like this:
s = s.strip(" ")
This will strip any space,
The examples above only remove strings from the left-hand and right-hand sides of strings. If you want to also remove characters from the middle of a string, try
import re print(re.sub("[s+]", "", s))
That should print out: