我正在尝试获取一个单词中的两个随机字符(而不是第一个或最后一个),并交换它们。例如。word = wrod,什么=什么。然而,我的代码只是将第一个随机字母替换为第二个随机字母,而不是交换它们。有什么办法可以解决这个问题吗?
#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)发布于 2021-03-22 21:56:42
使用pop函数,这将记住并删除索引中的字符。将字符串转换为word first tho,如下所示。
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)发布于 2021-03-22 22:10:53
你的“随机”代码看起来很好,但是问题出在你的替换代码上。我建议使用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)https://stackoverflow.com/questions/66747420
复制相似问题