首页 > 解决方案 > Python 3.6:在字符串中移动单词

问题描述

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

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

标签: pythonpython-3.x

解决方案


你可以这样做:

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)

推荐阅读