How to remove white spaces from a string in Python?

前端 未结 6 1832
小蘑菇
小蘑菇 2020-12-10 00:27

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

str1 = \"TN 81 NZ 0025\"

str1sp = nospace(srt1)

print(str1sp)

>>>TN81NZ0025
         


        
6条回答
  •  一个人的身影
    2020-12-10 00:36

    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'
    

提交回复
热议问题