The method of removing a string spaces in Python

Method One: strip method, remove the string leftmost and rightmost spaces

string = '  a  b  c   '

print( string.strip() )

#OUTPUT

>>'a b c'

 

Method Two: lstrip method, remove the string leftmost spaces

print( string.lstrip() )

#OUTPUT

>>'a b c  '

 

Method three: rstrip method, remove the rightmost spaces

>>'  a b c'

 

Method four: replace method to replace the space with other characters

print( string.replace( ' ' , '' ) )

#OUTPUT

>>'abc'

Method five: split + join method, press a blank string into the list, and then merge

tmp_str = string.split() # tmp_str = ['a' ,'b' ,'c']

str = '' .join (tmp_str) # by an empty string join list

print(str)

#OUTPUT

>>'abc'

Or directly merging step:

print( ''.join(string.split()) )

Guess you like

Origin www.cnblogs.com/zhanghengyu/p/11121160.html