- 3
How to remove whitespaces from a string in Python?
10 Antworten
+ 5
strip() removes leading and trailing whitespace but not internal.
+ 3
"".join(<string>.split()) 😁
+ 1
Have you just answered your own question?!?
Why?
Edit: there is also a mistake in your answer...
0
<string>.split()
0
Vishal Gautam
Use regex and .strip(). For example:
import re
my_string = "some unmeaning text about nothing "
my_string = re.sub(' +', ' ', my_string).strip()
print(my_string)
- 4
To remove the whitespaces and trailing spaces from the string, Python providies strip([str]) built-in function. This function returns a copy of the string after removing whitespaces if present. Otherwise returns original string.
string = " sololearn "
string2 = " sololearn "
string3 = " sololearn"
print(string)
print(string2)
print(string3)
print("After stripping all have placed in a sequence:")
print(string.strip())
print(string2.strip())
print(string3.strip())
sololearn
sololearn
sololearn
After stripping all have placed in a sequence:
sololearn
sololearn
sololearn