Python – How to Remove White Spaces from a String

pythonpython-2.7python-3.xstringwhitespace

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

str1 = "TN 81 NZ 0025"

str1sp = nospace(srt1)

print(str1sp)

>>>TN81NZ0025

Best Answer

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'
Related Question