How to remove white spaces from a string in Python?

前端 未结 6 1831
小蘑菇
小蘑菇 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:45

    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'
    

提交回复
热议问题