Skip to main content
 首页 » 编程设计

python之搜索字符串后打印文本

2024年11月01日21JustinYoung

我正在按照教程识别和打印特定字符串之间的单词;

f 是字符串 Mango grapes Lemon Ginger Pineapple

def findFruit(f): 
    global fruit 
    found = [re.search(r'(.*?) (Lemon) (.*?)$', word) for word in f] 
        for i in found: 
            if i is not None: 
                fruit = i.group(1) 
                fruit = i.group(3) 

grapes 和 Ginger 将在我打印 fruit 时输出。但是,我希望输出看起来像 "grapes"# "Ginger"(注意 "" 和 # 符号)。

请您参考如下方法:

您可以使用 string formatting这里使用str.format()功能:

def findFruit(f): 
    found = re.search(r'.*? (.*?) Lemon (.*?) .*?$', f) 
    if found is not None: 
       print '"{}" # "{}"'.format(found.group(1), found.group(2)) 

或者,Kimvais 在评论中发布了一个可爱的解决方案:

print '"{0}" # "{1}"'.format(*found.groups()) 

我已经做了一些编辑。首先,这里不需要 for 循环(也不需要列表理解。您正在遍历字符串的每个字母,而不是每个单词。即便如此,您也不想遍历每个单词。

我还更改了您的正则表达式(请注意,我的正则表达式不是那么好,所以可能有更好的解决方案)。