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

Python Remove Leading and Trailing Spaces from a String

Python Remove Leading and Trailing Spaces from a String

Document Object Reference Manual Python3 Examples

In Python, to remove leading and trailing spaces from a string you can use strip() method.

Here is an example of how to use it:

Example

original_string

=

" This is a string with spaces "

stripped_string

=

original_string.

strip

(

)

print

(

stripped_string

)

Running the code above removes the leading and trailing spaces, producing the following output:

这是一个带有空格的字符串

However, if the string contains characters such as \n and you only want to remove spaces, you need to specify that explicitly on the strip() method, as shown in the following code:

Example

my_string

=

" \nPython "

print

(

my_string.

strip

(

" "

)

)

The output is:





Python

We can also use a regular expression to remove leading and trailing spaces:

Example

import

re

my_string  

=

" Hello Python "

output

=

re

.

sub

(

r

'^\s+|\s+$'

,

''

,

my_string

)

print

(

output

)

Running the code above produces the following output:

Hello python

The strip() method removes all spaces at the beginning and end of a string (including spaces, tabs and newlines).

In addition, Python provides two methods for removing spaces from the beginning and end of a string:

Example

original_string

=

" This is a string with spaces "

left_stripped_string

=

original_string.

lstrip

(

)

 

Remove leading spaces

right_stripped_string

=

original_string.

rstrip

(

)

 

Remove trailing spaces

print

(

left_stripped_string

)

print

(

right_stripped_string

)

Running the code above produces the following output:

这是一个带有空格的字符串   

   这是一个带有空格的字符串

Document Object Reference Manual Python3 Examples