How to remove white spaces from a string in Python?

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

    One line of code to remove all extra spaces before, after, and within a sentence:

    string = "  TN 81 NZ 0025  "
    string = ''.join(filter(None,string.split(' ')))
    

    Explanation:

    1. Split entire string into list.
    2. Filter empty elements from list.
    3. Rejoin remaining elements with nothing

提交回复
热议问题