2017-03-07 188 views
-2

以下用於替換「。」的Python代碼有什麼問題?與「 - 」替換字符串中的字符?

x = 'BRK.B' 
if "." in x 
    spot = x.find('.') 
    x(spot)="-" 
+1

不應該是x [spot] !!而不是x(現貨)! –

+0

如果你想替換..使用x.replace(「。」,「 - 」) –

+2

@KeerthanaPrabhakaran並沒有真正有所作爲,因爲Python字符串是不可變的。無論哪種方式不起作用。兩者都導致「TypeError」 – DeepSpace

回答

1

你有一些錯別字,讓你的代碼無法工作。

即使您修復此問題,x是一個字符串,並且字符串不可變。可以使用str.replace

x = x.replace('.','-') 
+4

,這應該是一個評論! –

+0

人們經常寫出滿足OPs問題的最短答案,然後一致地闡述。可能是你們人們不喜歡那樣。 –

+0

不是真的!而這是無論如何可能重複的http://stackoverflow.com/questions/1228299/change-one-character-in-a-string-in-python –

1

你可以只使用replace

>>> 'BRK.B'.replace('.', '-') 
'BRK-B' 

如果你只是想更換一次出現:

>>> 'BRK.B'.replace('.', '-', 1) 
'BRK-B' 

如果由於某種原因,你真的想自己做:

x = 'BRK.B' 
if "." in x: # <- Don't forget : after x 
    spot = x.find('.') 
    # You're not allowed to modify x, but you can create a new string 
    x = x[:spot] + '-' + x[spot+1:] 
print(x) 
# 'BRK-B'