A simple way to remove string spaces in python

  • 2021-08-31 08:15:08
  • OfStack

python programming, we modify the code, encountered a lot of spaces, we want to delete spaces. In this article, this site has sorted out three ways to remove spaces from strings:

Method 1: Use the string function replace to remove all spaces.

Example:


>>> a = " a b c "
>>> a.replace(" ", "")
'abc'

Method 2: Use the string function split to remove the spaces at the beginning or end of the string.

Example:


>>> a = ''.join(a.split())
>>> print(a)
helloworld

Method 3: Use the join () method + split () method to remove all spaces.

Syntax:


str.join(sequence)

python Instance extension to remove spaces from strings

Example 1:


In[2]: a='   ddd dfe dfd   efre  ddd  '
In[3]: a
Out[3]: '   ddd dfe dfd   efre  ddd  '
In[4]: a.strip()
Out[4]: 'ddd dfe dfd   efre  ddd'
In[5]: a.lstrip()
Out[5]: 'ddd dfe dfd   efre  ddd  '
In[6]: a.rstrip()
Out[6]: '   ddd dfe dfd   efre  ddd'
In[7]: a.replace(' ','')
Out[7]: 'ddddfedfdefreddd'
In[8]: a.split()
Out[8]: ['ddd', 'dfe', 'dfd', 'efre', 'ddd']

Example 2:


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*']

Related articles: