如何在字符串中切换文本?

时间:2019-04-19 07:50:29

标签: python python-3.x

我想切换文本,但我总是失败。

假设我要切换

IWe中的x='I are We' 我尝试过

x=x.replace('I','We').replace('We','I')

但是很明显它将打印I are I

有人可以帮忙吗?

6 个答案:

答案 0 :(得分:2)

您可以使用正则表达式来避免多次遍历字符串(每次替换都要遍历列表),并使其更具可读性!它也适用于多个出现的单词。

string = 'I are We, I'

import re

replacements = {'I': 'We', 'We': 'I'}
print(re.sub("I|We", lambda x: replacements[x.group()], string)) # Matching words you want to replace, and replace them using a dict

输出

"We are I, We"

答案 1 :(得分:1)

这有点笨拙,但我倾向于按照以下方式做一些事情

x='I are We'
x=x.replace('I','we')
x=x.replace('We','I')
x=x.replace('we','We')

可以缩短为

`x = x.replace('I','we')。replace('We','I')。replace('we','We')

答案 2 :(得分:1)

x='I are We'
x=x.replace('I','You').replace('We','I').replace('You','We')
>>> x
'We are I'

答案 3 :(得分:1)

您可以将re.sub与函数一起使用:

In [9]: import re

In [10]: x = 'I are We'

In [11]: re.sub('I|We', lambda match: 'We' if match.group(0) == 'I' else 'I', x)
Out[11]: 'We are I'

如果您需要替换两个以上的子字符串,则可能需要创建一个像d = {'I': 'We', 'We': 'I', 'You': 'Not You'}这样的字典,并选择像lambda match: d[match.group(0)]这样的正确替换。您可能还想根据替换字符串动态构造正则表达式,但请确保对它们进行转义:

In [14]: d = {'We': 'I', 'I': 'We', 'ar|e': 'am'}

In [15]: re.sub('|'.join(map(re.escape, d.keys())), lambda match: d[match.group(0)], 'We ar|e I')
Out[15]: 'I am We'

答案 4 :(得分:0)

这并没有使用replace,但我希望它会有所帮助:

s = "I are We"
d = {"I": "We", "We": "I"}

" ".join([d.get(x, x) for x in s.split()])

>>> 'We are I'

答案 5 :(得分:0)

x='I are We'
dic = {'I':'We','We':'I'}
sol = []
for i in x.split():
    if i in dic:
        sol.append(dic[i])
    else:
        sol.append(i)

result = ' '.join(sol)
print(result)