Python Remove Spaces from a String
In Python, we can use several methods to remove spaces from a string. The most common is to use the strip()、lstrip() and rstrip() function, or to use the replace() function to replace spaces.
Method 1: use strip() function
strip() The function removes spaces at the beginning and end of a string.
Example
text
=
" Hello, World! "
trimmed_text
=
text.
strip
(
)
(
trimmed_text
)
Code analysis:
text.strip(): Remove the spaces at the beginning and end of the stringtext.print(trimmed_text): Print the string after the spaces are removed.
Output result:
Hello, World!
Method 2: use lstrip() and rstrip() function
lstrip() removes spaces at the beginning of a string, andrstrip() removes spaces at the end of a string.
Example
text
=
" Hello, World! "
left_trimmed_text
=
text.
lstrip
(
)
right_trimmed_text
=
text.
rstrip
(
)
(
left_trimmed_text
)
(
right_trimmed_text
)
Code analysis:
text.lstrip(): Remove the spaces at the beginning and end of the stringtextthe spaces at the beginning.text.rstrip(): Remove the spaces at the beginning and end of the stringtextthe spaces at the end.print(left_trimmed_text): Print the string after leading spaces are removed.print(right_trimmed_text): Print the string after trailing spaces are removed.
Output result:
Hello, World!
Hello, World!
Method 3: use replace() function
replace() The function can replace the spaces in a string with other characters (or with an empty character).
Example
text
=
" Hello, World! "
no_spaces_text
=
text.
replace
(
" "
,
""
)
(
no_spaces_text
)
Code analysis:
text.replace(" ", ""): Split the stringtextReplace all spaces in with an empty character (that is, delete the spaces).print(no_spaces_text): Print the string after all spaces are deleted.
Output result:
Hello,World!
Method 4: use split() and join() function
split() The function can split a string into a list by spaces, and thejoin() function can join the elements of a list into a string.
Example
text
=
" Hello, World! "
words
=
text.
split
(
)
no_spaces_text
=
""
.
join
(
words
)
(
no_spaces_text
)
Code analysis:
text.split(): Split the stringtextSplit into a list by spaceswords。"".join(words): Join the elements of the listwordsinto a string with no spaces in between.print(no_spaces_text): Print the joined string.
Output result:
Hello,World!
These methods can be chosen according to different needs. If you only need to remove spaces at the beginning and end of a string,strip() is the simplest choice. If you need to remove all spaces from a string,replace() or split() + join() is the better choice.
Python3 Examples