gpt4 book ai didi

python 3.6 : Moving around words within a string

转载 作者:行者123 更新时间:2023-11-28 20:33:34 26 4
gpt4 key购买 nike

我知道这个函数会围绕字符串中的字符移动,例如:

def swapping(a, b, c):
x = list(a)
x[b], x[c] = x[c], x[b]
return ''.join(x)

这让我可以这样做:

swapping('abcde', 1, 3)
'adcbe'
swapping('abcde', 0, 1)
'bacde'

但是我怎样才能让它做这样的事情,所以我不只是四处移动字母?这就是我想要完成的:

swapping("Boys and girls left the school.", "boys", "girls")
swapping("Boys and girls left the school.", "GIRLS", "bOYS")
should both have an output: "GIRLS and BOYS left the school."
# Basically swapping the words that are typed out after writing down a string

最佳答案

你可以这样做:

def swap(word_string, word1, word2):
words = word_string.split()
try:
idx1 = words.index(word1)
idx2 = words.index(word2)
words[idx1], words[idx2] = words[idx2],words[idx1]
except ValueError:
pass
return ' '.join(words)

关于 python 3.6 : Moving around words within a string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50337468/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com