關於Python去掉字串中的空格

2021-08-09 22:25:43 字數 500 閱讀 8854

經常會遇到需要將字串中的空格去掉的情況,通常我們有三種解決方法:

1、strip(char)方法:該方法是不能將字串中間的空格去掉的!!

>>> a = '  wode  ge  niu  '

>>> a.strip()

'wode  ge  niu'

>>> a = '  wode  ge  niu  '

>>> a.lstrip()

'wode  ge  niu  '

>>> a = '  wode  ge  niu  '

>>> a.rstrip()

'  wode  ge  niu'

2.>>> a = '  wode  ge  niu  '

>>> a.replace(' ','')

'wodegeniu'

3.>>> a = '  wode  ge  niu  '

>>> ''.join(a.split())

'wodegeniu'

python中去掉字串中的空格

我們想去除字串中不必要的空格時可以使用如下方法 在這裡以str作為例子來演示。在str中前中後三處都有空格。函式原型 宣告 str為字串,rm為要刪除的字串行 str.strip rm 刪除s字串中開頭 結尾處,位於 rm刪除序列的字元 str.lstrip rm 刪除s字串中開頭 左邊 處,位於 ...

去掉字串中的重複字元

題目 通過鍵盤輸入一串小寫字母 a z 組成的字串。請編寫乙個字串 過濾程式,若字串中出現多個相同的字元,將非首次出現的字元過濾掉。比如字串 abacacde 過濾結果為 abcde 要求實現函式 void stringfilter const char pinputstr,long linputl...

python去掉字串中的標點符號

方法1 使用列表新增每個字元,最後將列表拼接成字串import string defremovepunctuation text temp for c in text if c not in string.punctuation newtext join temp print newtext tex...