首页 > 解决方案 > 试图找出一种在字符串中交换字符的方法(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)

标签: pythonrandomswap

解决方案


您的“随机”代码看起来不错,但是是的,问题出在您的替换上。我建议使用 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)

推荐阅读