[英]Trying to figure out a way to swap characters within a string (python)
我試圖在一個單詞中獲取兩個隨機字符(不是第一個或最后一個)並交換它們。 前任。 詞= wod,什么= waht。 然而,我的代碼只是用第二個隨機字母替換第一個隨機字母,而不是交換它們。 有沒有解決的辦法?
#Input
word = str(input("Please enter your word here: "))
#Processing/Functions/Output
#Only scramble if word has more than 3 letters
if len(word) > 3:
#randompick picks random positions in the word
def randompick() :
#Pick random positions
pos1 = randint(1, len(word)-2)
pos2 = randint(1, len(word)-2)
#Make sure second position isn't the same as the first
while pos1 == pos2:
pos2 = randint(1, len(word)-2)
#assign letters to variables
firstLetter = word[pos1]
secondLetter = word[pos2]
#run scramble function
#return firstLetter, secondLetter
scramble(firstLetter, secondLetter)
#scramble swaps the two positions previously chosen in randompick
def scramble(firstLetter, secondLetter):
scrambled_word = word.replace(firstLetter, secondLetter) #first replacement
print (scrambled_word)
#Run functions
randompick()
else:
print (word)
使用 function pop,這將記住並按索引刪除字符。 首先將字符串轉換為單詞,如此處所示。
word = ['w','o','r','d'];
print("result before swap: ", word)
randompos1 = 1
randompos2 = 2
word.insert(randompos1, word.pop(randompos2))
word.insert(randompos2, word.pop(randompos1+1))
print("result after swap: ", word)
您的“隨機”代碼看起來不錯,但是是的,問題出在您的替換上。 我建議使用 python 列表切片。
firstLetter = word[pos1]
secondLetter = word[pos2]
if pos1 > pos2:
before = word[:pos1]
between = word[pos1 + 1:pos2]
after = word[pos2 + 1:]
print(before + secondLetter + between + firstLetter + after)
else:
before = word[:pos2]
between = word[pos2 + 1:pos1]
after = word[pos1 + 1:]
print(before + secondLetter + between + firstLetter + after)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.