首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python 3.6:在字符串中移动单词

Python 3.6:在字符串中移动单词
EN

Stack Overflow用户
提问于 2018-05-14 19:13:06
回答 4查看 629关注 0票数 2

我知道这个函数在字符串中围绕字符移动,如下所示:

代码语言:javascript
复制
def swapping(a, b, c):
    x = list(a)
    x[b], x[c] = x[c], x[b]
    return ''.join(x)

这让我可以这么做:

代码语言:javascript
复制
swapping('abcde', 1, 3)
'adcbe'
swapping('abcde', 0, 1)
'bacde'

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

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

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-05-14 20:16:08

使用正则表达式和替换函数(可以使用lambda和双三元函数完成,但这并不是真正的可读性)

匹配所有单词(\w+),并与两个单词(大小写不敏感)进行比较。如果发现,返回“相反的”字。

代码语言:javascript
复制
import re

def swapping(a,b,c):
    def matchfunc(m):
        g = m.group(1).lower()
        if g == c.lower():
            return b.upper()
        elif g == b.lower():
            return c.upper()
        else:
            return m.group(1)

    return re.sub("(\w+)",matchfunc,a)

print(swapping("Boys and girls left the school.", "boys", "girls"))
print(swapping("Boys and girls left the school.", "GIRLS", "bOYS"))

两种打印:GIRLS and BOYS left the school.

票数 2
EN

Stack Overflow用户

发布于 2018-05-14 19:19:28

你可以这样做:

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

Stack Overflow用户

发布于 2018-05-14 19:19:27

使用split函数获取由whitespaces分隔的单词列表

代码语言:javascript
复制
def swapping(a, b, c):
x = a.split(" ")
x[b], x[c] = x[c], x[b]
return ' '.join(x)

如果希望将字符串作为参数传递,请使用.index()获取要交换的字符串的索引。

代码语言:javascript
复制
def swapping(a, b, c):
x = a.split(" ")
index_1 = x.index(b)
index_2 = x.index(c)
x[index_2], x[index_1] = x[index_1], x[index_2]
return ' '.join(x)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50337468

复制
相关文章

相似问题

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