如何解决试图找出一种在字符串中交换字符的方法python
我试图在一个单词中获取两个随机字符(不是第一个或最后一个)并交换它们。前任。 word = wrod,what = 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)
解决方法
使用函数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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。