如果满足条件,则用字符串中的另一个替换单词

时间:2015-03-09 19:19:07

标签: python-2.7

如果条件为true,我正在尝试使用函数替换字符串中的两个单词。 条件是:如果单词“poor”跟在“not”后面,则将整个字符串“not ... poor”替换为“rich”。问题是我不知道如何制作这个功能 - 更具体的说明如何制作一个函数来寻找穷人这个词不是跟着什么,然后我必须写什么才能做出替换。我对python很新,所以也许这是一个愚蠢的问题,但我希望有人会帮助我。

我希望函数执行以下操作:

string = 'I am not that poor' 

new_string = 'I am rich' 

3 个答案:

答案 0 :(得分:0)

第一步:确定'不是'和“穷人”#39;在你的字符串里面(查看https://docs.python.org/2.7/library/stdtypes.html#string-methods

第二步:比较' not'的位置。和“穷人”#39;你刚刚找到的。穷人'来之后不是'?你怎么能说出来的?你应该考虑额外的边缘情况吗?

第三步:如果你的条件不符合,什么也不做。如果是,那么包括“不”之间的所有内容都包括在内。和“穷人”#39;必须被“富人”取代。鉴于上述文档链接,我将让您决定如何做到这一点。

祝你好运,编码愉快!

答案 1 :(得分:0)

毫无疑问,可以改进正则表达式模式,但是使用Python的re模块快速而肮脏的方法:

import re
patt = 'not\s+(.+\s)?poor'
s = 'I am not that poor'
sub_s = re.sub(patt, 'rich', s)
print s, '->', sub_s
s2 = 'I am not poor'
sub_s2 = re.sub(patt, 'rich', s2)
print s2, '->', sub_s2
s3 = 'I am poor not'
sub_s3 = re.sub(patt, 'rich', s3)
print s3, '->', sub_s3

输出:

I am not that poor -> I am rich
I am not poor -> I am rich
I am poor not -> I am poor not

正则表达式模式patt匹配文本not后跟空格和(可选)其他字符后跟空格,然后匹配单词poor

答案 2 :(得分:0)

这是我想出来的。适用于您的示例,但需要调整(如果在非穷人之间有多于1个单词,那该怎么办)。

my_string = 'I am not that poor'
print my_string
my_list = my_string.split(' ')

poor_pos = my_list.index('poor')
if my_list[poor_pos - 1] or my_list[poor_pos - 2] == 'not':
    not_pos = my_list.index('not')
    del my_list[not_pos:poor_pos+1]
    my_list.append('rich')

print " ".join(word for word in my_list)

输出:

I am not that poor
I am rich
相关问题