Python Remove Leading and Trailing Spaces from a String
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
(
)
(
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 "
(
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
)
(
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:
- lstrip() -- Remove the spaces at the beginning of the string.
- rstrip() -- Remove the spaces at the end of the 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
(
left_stripped_string
)
(
right_stripped_string
)
Running the code above produces the following output:
这是一个带有空格的字符串
这是一个带有空格的字符串
Python3 Examples