python - 试图找出一种在字符串中交换字符的方法(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)
解决方案
您的“随机”代码看起来不错,但是是的,问题出在您的替换上。我建议使用 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)
推荐阅读
- css - Sass 可以识别大小并应用条件吗?
- java - 如何检查 url 在 java 中是否存在?
- javascript - NestJS NATS 请求-响应
- java - 随机增加访问次数JSP
- javascript - 为什么没有调用 window.scrollTo() ?
- ios - 判断是否触发了本地通知
- bash - 列表中的平均分
- python - 连接到 Redis 的 Azure 缓存时,Azure 环境变量从提供“无效密码”的键中删除最后一个字符 ('=')
- visual-studio - Visual Studio 分支比较给出误报。相同的文件被标记为不同
- r - 在 ggplotly 中使用 geom_tile 的颜色美学