python - 提示用户输入()并使用正则表达式
问题描述
我想使用正则表达式打印在另一个文本中找到的列表中的所有文本片段。这两个文本都是由用户和名称提示的(只是名称,与鸡蛋无关)egg
。egg_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)
解决方案
如果要在egg
(ie egg = "up"
) 中查找 ( egg_carton
ie ) 的值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
推荐阅读
- node.js - 在我的node.js应用程序中使用mongodb和mongoose在Mocha和Chai上运行测试后无法清除数据库
- c++ - C++ 类实例未初始化但没有编译错误,为什么
- spring - 当从不使用附加程序时,我希望不创建 Logback 文件。[滚动文件附加器]
- cassandra - Cassandra 时间点恢复
- python - Venv 在 CentOS 中失败,确保 pip 丢失
- c++ - 我可以检测哪些类型在用作基类时可能与其派生类重叠
- android - 如何以编程方式在 Android 中设置 DNS1 和 DNS2 以及如何检查 DNS 是否设置?
- angular - 如何删除 Angular 7 中的引导工具栏?
- postgresql - 在 Postgres 函数中使用参数作为列名
- hadoop - 使用 Hive 计算文本变量的单词频率