嗨我想編寫一個函數來交換字符串中的2個字符。例如,如果輸入交換('12345',2,3),返回結果應爲'13245' 我寫下面的函數,但我得到錯誤消息說''int'對象不可以自訂',爲什麼?字符串中的交換字符
def swap(x,a,b):
tempa = x[a]
tempb = x[b]
i=0
listx = list(x)
while i<len(listx):
if i==a:
listx[a] = tempb
elif i==b:
listx[b] = tempa
i=i+1
return listx
我想你的代碼,它給了另一個錯誤消息: 類型錯誤: '詮釋' 對象不是可迭代 ,所以我編輯它是 高清WAP(some_character,A,B): \t some_list =名單(STR( some_character)) \t some_list [a-1],some_list [b-1] = some_list [b-1],some_list [a-1]#減去-1以參考它們的實際索引 \t return float(''。加入(some_list))#準備新的字符串 – Jasmine
那麼它會出現,你的問題是你稱它爲swap(12345,2,3)而不是swap(「12345」,2,3) ' - 沒有引號,你傳遞一個int,而不是一個字符串。 – Travis
@Jasmine你確定你沒有給一個數字作爲'some_character'的輸入嗎? –