首页 > 解决方案 > 提示用户输入()并使用正则表达式

问题描述

我想使用正则表达式打印在另一个文本中找到的列表中的所有文本片段。这两个文本都是由用户和名称提示的(只是名称,与鸡蛋无关)eggegg_carton以下代码打印一个空列表。我认为问题是re.compile代码的一部分,但我不知道如何解决这个问题。我想要以它的形式修改的代码,而不是解决这个问题的完全其他方法。欣赏它。

import re
egg= input()
egg_carton = input()
text_fragment = re.compile(r'(egg)')
find_all = text_fragment.findall(egg_carton)
print(find_all)

标签: python

解决方案


如果要在egg(ie egg = "up") 中查找 ( egg_cartonie ) 的值egg_carton = "upupupup",则需要使用:

text_fragment = re.compile(r'({0})'.format(egg))

.format(egg)转换为包含的{0}egg。因此,如果egg = "up",则等价于:

text_fragment = re.compile(r'(up)')

把这一切放在一起:

import re
egg= raw_input()
egg_carton = raw_input()
text_fragment = re.compile(r'({0})'.format(egg)) # same as: re.compile(r'(up)')
find_all = text_fragment.findall(egg_carton)
print(find_all)

给我这个输出:

['up', 'up', 'up', 'up']

您可以在 Python3 文档中找到有关该"string".format()函数的更多信息:https ://docs.python.org/3.4/library/functions.html#format


推荐阅读