2015-09-29 50 views
1

嗨我想編寫一個函數來交換字符串中的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 

回答

1

你也可以做到這一點通過以下方式:

In [1]: def swap(some_character, a, b): 
    ....:  some_list = list(some_character) 
    ....:  some_list[a-1], some_list[b-1] = some_list[b-1], some_list[a-1] # subtracted -1 to refer to their actual indexes 
    ....:  return ''.join(some_list) # prepare new string 
    ....: 

In [2]: swap('12345', 2,3) 
Out[2]: '13245' 

In [3]: swap('abcdefg', 3,5) 
Out[3]: 'abedcfg' 
+0

我想你的代碼,它給了另一個錯誤消息: 類型錯誤: '詮釋' 對象不是可迭代 ,所以我編輯它是 高清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

+1

那麼它會出現,你的問題是你稱它爲swap(12345,2,3)而不是swap(「12345」,2,3) ' - 沒有引號,你傳遞一個int,而不是一個字符串。 – Travis

+0

@Jasmine你確定你沒有給一個數字作爲'some_character'的輸入嗎? –

0

不知道your're問爲什麼你的代碼不能正常工作,或者如果你想找到一個更好的交換功能但無論如何,這裏有一個更好的交換功能:

def swap(s, a, b): 
    return s[:a-1] + s[b-1] + s[a:b-1] + s[a-1] + s[b:] 

的想法是,每串有兩個交換角色,它們將字符串轉換成開始,中間和結束串。這個函數只是連接交換的字母和子字符串。

你給的代碼(和Rahul Gupta的)運行沒有錯誤。你的函數和這兩個答案的區別在於我們的函數返回一個字符串並使用基於0的索引,而你的函數返回一個列表並使用基於1的索引。