Python 中去除字符串空格的方法


方法一:strip方法 , 去除字符串最左和最右的空格

string = '  a  b  c   '

print( string.strip() )

#OUTPUT

>>'a b c'

 

方法二:lstrip方法, 去除字符串最左的空格

print( string.lstrip() )

#OUTPUT

>>'a b c  '

 

方法三:rstrip方法, 去除最右的空格

>>'  a b c'

 

方法四:replace方法, 把空格替換為其他字符

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

#OUTPUT

>>'abc'

方法五:split + join方法,先按空格把字符串化成一個列表,再合並

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

str = ''.join(tmp_str) #用一個空字符串join列表

print(str)

#OUTPUT

>>'abc'

或者直接合並步驟:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM