Home >Backend Development >Python Tutorial >How to remove spaces in python

How to remove spaces in python

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-06-22 10:41:057187browse

How to remove spaces in python

How to remove spaces in python? Here are some common methods:

a='     ddd dfe dfd     efre    ddd   '
a
'     ddd dfe dfd     efre    ddd   '

1.strip(): Remove the leading and trailing spaces

a.strip()
'ddd dfe dfd     efre    ddd'

2 .lstrip(): Remove the spaces on the left

In[5]: a.lstrip()
Out[5]: 'ddd dfe dfd     efre    ddd   '

3.rstrip(): Remove the spaces on the right

Related recommendations: " Python Video Tutorial

In[6]: a.rstrip()
Out[6]: '     ddd dfe dfd     efre    ddd'

4.replace('c1','c2'): Replace c1 in the string with c2. Therefore, you can use replace(' ','') to remove all spaces in the string

In[7]: a.replace(' ','')
Out[7]: 'ddddfedfdefreddd'

5.split(): Slice the string by specifying the delimiter. If the parameter If num has a specified value, only num substrings are separated

In[8]: a.split()
Out[8]: ['ddd', 'dfe', 'dfd', 'efre', 'ddd']
In[3]: a = 'dfdfd*dfjdf**fdjfd*22*'
In[4]: a
Out[4]: 'dfdfd*dfjdf**fdjfd*22*'
In[5]: a.split('*')
Out[5]: ['dfdfd', 'dfjdf', '', 'fdjfd', '22', '']
In[6]: a.split('*',2)
Out[6]: ['dfdfd', 'dfjdf', '*fdjfd*22*']

6. Use regular expressions

>>> re.split(r'\s+', 'a b   c')
['a', 'b', 'c']

The above is the detailed content of How to remove spaces in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn