1

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)
11
  • 3
    Can you provide some sample input (and the value of egg with that sample input)? Commented Jun 24, 2018 at 11:58
  • So if the user writes egg = up and egg_carton = upupupup the program should output [up, up, up, up] Commented Jun 24, 2018 at 12:01
  • 2
    Agree with @kabanus. If you want to look for the value of egg in egg_carton, then you need to use: text_fragment = re.compile(r'({0})'.format(egg)). The .format(egg) converts {0} to contain the value of egg. Commented Jun 24, 2018 at 12:04
  • 1
    Yes so if egg = "up", then re.compile(r'({0})').format(egg)) is equivalent to re.compile(r'(up)') Commented Jun 24, 2018 at 12:06
  • 1
    Look up string formatting with .format in the Python specifications for your version. Commented Jun 24, 2018 at 12:17

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.