简体   繁体   中英

How to remove white spaces from a string in Python?

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

str1 = "TN 81 NZ 0025"

str1sp = nospace(srt1)

print(str1sp)

>>>TN81NZ0025

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'

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'

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.

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

Try this:

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM