How to remove whitespaces from a string in Python? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
- 3

How to remove whitespaces from a string in Python?

7th Feb 2021, 4:40 AM
Vishal Gautam
Vishal Gautam - avatar
8 ответов
+ 5
strip() removes leading and trailing whitespace but not internal.
7th Feb 2021, 7:38 AM
David Ashton
David Ashton - avatar
+ 3
"".join(<string>.split()) 😁
7th Feb 2021, 4:44 AM
David Ashton
David Ashton - avatar
+ 1
Have you just answered your own question?!? Why? Edit: there is also a mistake in your answer...
7th Feb 2021, 4:49 AM
Angelo
Angelo - avatar
+ 1
Sorry, I didn't knew about it, thank you David Ashton
7th Feb 2021, 7:44 AM
∆BH∆Y
∆BH∆Y - avatar
0
<string>.split()
7th Feb 2021, 4:42 AM
Slick
Slick - avatar
0
str1 = ' xyz ' print(str1.strip()) Or str1 = str1.strip() print(str1) Or If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.
7th Feb 2021, 4:59 AM
∆BH∆Y
∆BH∆Y - avatar
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)
7th Feb 2021, 8:29 AM
Valerii Mamontov
Valerii Mamontov - avatar
- 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
7th Feb 2021, 4:44 AM
Vishal Gautam
Vishal Gautam - avatar