首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试找出一种在字符串中交换字符的方法(python)

尝试找出一种在字符串中交换字符的方法(python)
EN

Stack Overflow用户
提问于 2021-03-22 21:52:08
回答 2查看 116关注 0票数 0

我正在尝试获取一个单词中的两个随机字符(而不是第一个或最后一个),并交换它们。例如。word = wrod,什么=什么。然而,我的代码只是将第一个随机字母替换为第二个随机字母,而不是交换它们。有什么办法可以解决这个问题吗?

代码语言:javascript
复制
#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)
EN

回答 2

Stack Overflow用户

发布于 2021-03-22 21:56:42

使用pop函数,这将记住并删除索引中的字符。将字符串转换为word first tho,如下所示。

代码语言:javascript
复制
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)
票数 0
EN

Stack Overflow用户

发布于 2021-03-22 22:10:53

你的“随机”代码看起来很好,但是问题出在你的替换代码上。我建议使用python列表切片。

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66747420

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档