我是字串新手,我試圖根據它們的索引交換字符
如果任一索引無效(即,除 0、1、2、...、len(x) - 1 之外的其他值),該函式應回傳 None。
x =0
i = 0
j = 0
def swap(x, i, j):
x = (input("Enter a string: "))
i = int(input("first number swap: "))
j = int(input("Second number swapped: "))
for ch in range(i, j):
print(x[i:j])
if ch not in range(i, j):
print("None")
swap(x, i, j)
我嘗試使用此函式,但我得到了基于輸入 j 的重復,減去基于輸入 i 排除的字母
#input for x = sloth
#input for i = 4
#input for j = 1
#will equal = lot x3
相反,我希望索引 4 處的字符與索引 1 處的字符切換,但如果它不在這些字符的范圍內,則程式應回傳“無”
誰能告訴我我做錯了什么?
uj5u.com熱心網友回復:
如果函式應該接受x, i, 和j作為引數,你應該使用這些引數,而不是input()在函式內部呼叫。如果要用于input()獲取引數,請在呼叫函式之前執行此操作。
由于字串是不可變的,你不能簡單地交換字符,所以我建議通過切片構建一個新字串:
def swap(x, i, j):
i, j = sorted((i, j))
try:
return x[:i] x[j] x[i 1:j] x[i] x[j 1:]
except IndexError:
return None
print(swap(
input("Enter a string: "),
int(input("first number swap: ")),
int(input("Second number swapped: "))
))
Enter a string: abcdefg
first number swap: 2
Second number swapped: 4
abedcfg
另一種選擇可能是轉換x為可變序列(如 a list),以便您可以進行交換,然后將join其轉換回字串以回傳它:
def swap(x, i, j):
y = list(x)
try:
y[i], y[j] = y[j], y[i]
return ''.join(y)
except IndexError:
return None
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/455720.html
