How to remove white spaces from a string in Python

2019-04-02 09:23发布

问题:

I need to remove spaces from a string in python. For example.

str1 = "TN 81 NZ 0025"

str1sp = nospace(srt1)

print(str1sp)

>>>TN81NZ0025

回答1:

Use str.replace:

>>> s = "TN 81 NZ 0025"
>>> s.replace(" ", "")
'TN81NZ0025'

To remove all types of white-space characters use str.translate:

>>> from string import whitespace
>>> s = "TN 81   NZ\t\t0025\nfoo"
# Python 2
>>> s.translate(None, whitespace)
'TN81NZ0025foo'
# Python 3
>>> s.translate(dict.fromkeys(map(ord, whitespace)))
'TN81NZ0025foo'


回答2:

You can replace every spaces by the string.replace() function:

>>> "TN 81 NZ 0025".replace(" ", "")
'TN81NZ0025'

Or every whitespaces caracthers (included \t and \n) with a regex:

>>> re.sub(r'\s+', '', "TN 81 NZ 0025")
'TN81NZ0025'
>>> re.sub(r'\s+', '', "TN 81 NZ\t0025")  # Note the \t character here
'TN81NZ0025'


回答3:

Mind that in python strings are immutable and string replace function returns a string with the replaced value. If you are not executing the statement at the shell but inside a file,

 new_str = old_str.replace(" ","" )

This will replace all the white spaces in the string. If you want to replace only the first n white spaces,

new_str = old_str.replace(" ","", n)

where n is a number.



回答4:

One line of code to remove all extra spaces before, after, and within a sentence:

string = "  TN 81 NZ 0025  "
string = ''.join(filter(None,string.split(' ')))

Explanation:

  1. Split entire string into list.
  2. Filter empty elements from list.
  3. Rejoin remaining elements with nothing


回答5:

Try this:

s = "TN 81 NZ 0025"
s = ''.join(s.split())


回答6:

You can replace multiple spaces into a desired pattern by using following ways. Here your pattern is blank string.

import re
pattern = ""
re.sub(r"\s+", pattern, your_string)

or

import re
pattern = ""
re.sub(r" +", "", your_string)