lundi 22 mars 2021

Trying to figure out a way to swap characters within a string (python)

I'm trying to get two random characters inside a word (not first or last) and swap them. Ex. word = wrod, what = waht. My code however, just replaces the first random letter with the second random letter instead of swapping them. Is there a way around this?

#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)



Aucun commentaire:

Enregistrer un commentaire