Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 532
Ufoguy Avatar asked Nov 27 '22 03:11

Ufoguy


2 Answers

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'
like image 169
Ashwini Chaudhary Avatar answered Dec 10 '22 16:12

Ashwini Chaudhary


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'
like image 33
Maxime Lorant Avatar answered Dec 10 '22 16:12

Maxime Lorant