Hi, I want to know How to remove whitespaces from a string in Python
# first you need a precise definition of the characters included in the term "whitespace"
# one such definition is provided in the string module
import string
the_whites = set(string.whitespace) # space, tab, linefeed, return, formfeed, and vertical tab
original_string = ' the frog jumped'
no_white = []
for char in original_string:
if char not in the_whites:
no_white.append(char)
no_white_string = ""
no_white_string = no_white_string.join(no_white)
print(original_string)
print(no_white_string)
How about:
new_string = "".join(old_string.split())
There is also
import re
new_string = re.sub(r"\s+", "", old_string)
1 Like