Python Remove Spaces from String
In Python, we can use multiple methods to remove spaces from a string. The most common method is to usestrip()、lstrip()andrstrip()function, or usereplace()function to replace spaces.
Method 1: Usingstrip()function
strip()The function is used to remove spaces at the beginning and end of the string.
Example
trimmed_text = text.strip()
print(trimmed_text)
Code Analysis:
text.strip(): remove the string'stextleading and trailing spaces.print(trimmed_text): output the string after removing spaces.
Output Result:
Hello, World!
Method 2: Usinglstrip()andrstrip()function
lstrip()is used to remove spaces at the beginning of the string,rstrip()is used to remove spaces at the end of the string.
Example
left_trimmed_text = text.lstrip()
right_trimmed_text = text.rstrip()
print(left_trimmed_text)
print(right_trimmed_text)
Code Analysis:
text.lstrip(): remove the string'stextleading spaces.text.rstrip(): remove the string'stexttrailing spaces.print(left_trimmed_text): output the string after removing leading spaces.print(right_trimmed_text): output the string after removing trailing spaces.
Output Result:
Hello, World! Hello, World!
Method 3: Usingreplace()function
replace()The function can replace spaces in a string with other characters (or an empty string).
Example
no_spaces_text = text.replace(" ", "")
print(no_spaces_text)
Code Analysis:
text.replace(" ", ""): replace the string'stextall spaces with an empty character (i.e., remove spaces).print(no_spaces_text): output the string after removing all spaces.
Output Result:
Hello,World!
Method 4: Usingsplit()andjoin()function
split()The function can split the string into a list by spaces,join()The function can join the elements in the list into a string.
Example
words = text.split()
no_spaces_text = "".join(words)
print(no_spaces_text)
Code Analysis:
text.split(): split the stringtextinto a list by spaces.words。"".join(words): join the list'swordselements into a string, with no spaces in between.print(no_spaces_text): output the joined string.
Output Result:
Hello,World!
These methods can be selected and used according to different needs. If you only need to remove spaces at the beginning and end of the string,strip()is the simplest choice. If you need to remove all spaces in the string,replace()orsplit() + join()is a better choice.
Python3 Examples