Liviu Iosif
Liviu Iosif

Reputation: 67

Prompting user input() and using regular expression

I want to use regular expression to print all the text fragments in a list found in another text. Both texts are prompted by the user and the names (egg and egg_carton are just names, it's not about eggs). The following code prints an empty list. I think the problem is the re.compile part of the code, but I don't know how to fix this problem. I would like the code modified in it's form, not a completely other method of solving this problem. Appreciate it.

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

Upvotes: 1

Views: 149

Answers (1)

rst-2cv
rst-2cv

Reputation: 1180

If you want to look for the value of egg (i.e. egg = "up") in egg_carton (i.e. egg_carton = "upupupup"), then you need to use:

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

The .format(egg) converts {0} to contain the value of egg. Therefore, if egg = "up", it would be equivalent to:

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

Putting this all together:

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)

Gives me this output:

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

You can find more information on the "string".format() function in the Python3 docs: https://docs.python.org/3.4/library/functions.html#format

Upvotes: 2

Related Questions