2014-03-27 56 views
0

我想用大寫字母I替換字符串中的任何字符。我有以下代碼:替換字符串不會改變值

str.replace('i ','I ') 

但是,它不會替換字符串中的任何內容。我希望在我之後加上一個空格,以區分任何我的言辭和言辭。

謝謝,如果你能提供幫助!

確切的代碼是:

new = old.replace('i ','I ') 
new = old.replace('-i-','-I-') 
+5

'replace'不會改變字符串到位。您必須將替換的字符串分配給變量。 – roippi

+0

對不起。我的確切代碼是: – user3449872

+0

爲什麼破折號? – wnnmaw

回答

2
new = old.replace('i ','I ') 
new = old.replace('-i-','-I-') 

你丟掉第一new當你將在它的第二次操作的結果。

要麼

​​

new = old.replace('i ','I ').replace('-i-','-I-') 

或使用正則表達式。

1

我認爲你需要這樣的事情。

>>> import re 
>>> s = "i am what i am, indeed." 
>>> re.sub(r'\bi\b', 'I', s) 
'I am what I am, indeed.' 

這將只替換裸'i'的與I,但'i'的是其他詞的一部分保持不變。

對於來自comments你的榜樣,你可能需要像這樣:

>>> s = 'i am sam\nsam I am\nThat Sam-i-am! indeed' 
>>> re.sub(r'\b(-?)i(-?)\b', r'\1I\2', s) 
'I am sam\nsam I am\nThat Sam-I-am! indeed'