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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With