[英]Prompting user input() and using regular expression
我想使用正則表達式將所有文本片段打印在另一個文本中找到的列表中。 這兩個文本均由用戶提示,並egg_carton
名稱( 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_carton
查找egg
的值(即egg = "up"
)(即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 docs中找到有關"string".format()
函數的更多信息: https ://docs.python.org/3.4/library/functions.html#format
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.