Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Remove Spaces from a String

Python Remove Spaces from a String

Document Object Reference Manual Python3 Examples

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

(

)

print

(

trimmed_text

)

Code analysis:

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

(

)

print

(

left_trimmed_text

)

print

(

right_trimmed_text

)

Code analysis:

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

(

" "

,

""

)

print

(

no_spaces_text

)

Code analysis:

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

)

print

(

no_spaces_text

)

Code analysis:

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.

Document Object Reference Manual Python3 Examples