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

How to remove spaces in python

爱喝马黛茶的安东尼
Release: 2019-06-22 10:41:05
Original
7205 people have browsed it

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   '
Copy after login

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

a.strip()
'ddd dfe dfd     efre    ddd'
Copy after login

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

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

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

Related recommendations: " Python Video Tutorial

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

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'
Copy after login

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']
Copy after login
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*']
Copy after login

6. Use regular expressions

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template