Ufoguy Ufoguy - 2 months ago 8
Python Question

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

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'