4 回答

TA貢獻2003條經驗 獲得超2個贊
三種方法如下:
用replace函數:
your_str.replace(' ', '')
a = 'hello word' # 把a字符串里的word替換為python
a.replace('word','python') # 輸出的結果是hello python
用split斷開再合上:
''.join(your_str.split())
用正則表達式來完成替換:
import re strinfo = re.compile('word')
b = strinfo.sub('python',a)
print b
# 結果:hello python

TA貢獻1829條經驗 獲得超6個贊
1、借助于lstrip()提取左邊空格
>>> s = ' A B C '
>>> s.lstrip() # 去除字母字符串左邊的空格
'A B C '
2、借助于rstrip()提取右邊空格
>>> s = " A B C "
>>> s.rstrip() # 去除字符串右邊的空格
' A B C'
3、借助于strip()提取左右兩邊的空格
>>> s = " A B C "
>>> s.strip() # 去除兩邊的空格
'A B C'
擴展資料
python對象的處理方法
對象的方法是指綁定到對象的函數。調用對象方法的語法是instance.method(arguments)。它等價于調用Class.method(instance, arguments)。
當定義對象方法時,必須顯式地定義第一個參數,一般該參數名都使用self,用于訪問對象的內部數據。
這里的self相當于C++, Java里面的this變量,但是我們還可以使用任何其它合法的參數名,比如this 和 mine 等,self與C++,Java里面的this不完全一樣,它可以被看作是一個習慣性的用法,我們傳入任何其它的合法名稱都行。

TA貢獻1874條經驗 獲得超12個贊
1 2 3 4 5 6 7 8 9 10 | #假如有個字符串s >>> s='a b c d b dd e' #看到此字符串。首先,先把s中的空格分開(默認是以空格為分割) >>> s.split() #然后再使用【,】分開字符串s >>> ','.join(s.split()) #最后效果為 >>> p=','.join(s.split()) >>> p 'a,b,c,d,b,dd,e' |
添加回答
舉報