How to remove white spaces from a string in Python?

前端 未结 6 1821
小蘑菇
小蘑菇 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条回答
  •  -上瘾入骨i
    2020-12-10 00:44

    Mind that in python strings are immutable and string replace function returns a string with the replaced value. If you are not executing the statement at the shell but inside a file,

     new_str = old_str.replace(" ","" )
    

    This will replace all the white spaces in the string. If you want to replace only the first n white spaces,

    new_str = old_str.replace(" ","", n)
    

    where n is a number.

提交回复
热议问题