2013-03-28 125 views
0

試圖僅按位置替換字符串中的字符。Python:按位置替換字符串中的字符

這是我的,任何幫助將不勝感激!

for i in pos: 
    string=string.replace(string[i],r.choice(data)) 
+0

爲什麼不把它作爲一個列表而不是字符串?那麼你可以做'newhand [i] = r.choice(cardset)' – 2013-03-28 03:44:14

+0

字符串是不可變的。創建一個新的 – JBernardo 2013-03-28 03:44:23

回答

1

爲什麼不直接更換呢?

for i in pos: 
    newhand=newhand.replace(newhand[i],r.choice(cardset)) 

去:

for i in pos: 
    newhand[i]=r.choice(cardset) 

這是假設hand是一個列表,而不是一個字符串。
如果hand是在程序中的這一點上串,
我推薦你把它作爲一個列表,字符串是不能被改變,因爲他們是immutable

如果你想保持手爲一個字符串,你總是可以做:

newhand = ''.join([(x,r.choice(cardset))[i in pos] for i,x in enumerate(newhand)]) 

但是,這將newhand轉換到一個列表,然後加入它變成一個字符串存儲它放回newhand之前。

此外,該行:

if isinstance(pos, int): 
       pos=(pos,) 

應改爲:

pos = [int(index) for index in pos.split(',')] 

你不需要isinstance,因爲這將始終返回false。

+0

我得到這個解決方案的錯誤: TypeError:'str'對象不支持項目分配 – user2218235 2013-03-28 03:52:27

+0

@ user2218235如果你想保持'手'作爲一個字符串使用第二種解決方案。 – Serdalis 2013-03-28 04:07:28

+0

非常感謝! – user2218235 2013-03-28 04:26:24

1

如果你想還繼續用繩子,這是解決方案:

newhand = '{0}{1}{2}'.format(newhand[:i], r.choice(cardset), newhand[i + 1:]) 
0

你的問題是與替換功能。當您調用替換函數時,它將用第二個參數替換第一個參數的ALL實例。如果newhand = AKAK9,newhand.replace(「A」,「Q」)將導致newhand = QKQK9。

如果可能的話,將字符串更改爲列表,然後執行以下操作來更改特定索引:

for i in pos: 
    newhand[i]=r.choice(cardset) 

如果需要的話,您可以通過使用STR改變newhand列表返回一個字符串() :

hand = ''.join(str(e) for e in newhand_list) 
+1

只有'hand'是一個'list',它不在他的程序中。 – Serdalis 2013-03-28 04:02:21

+0

你是對的,我更新了我的反應以反映這一點。 – 2013-03-28 04:04:17

+0

你不能使用'str'將'list'轉換爲'string'。 – Serdalis 2013-03-28 04:13:02