I am trying to select parts of a list using numbers that are input into the terminal using regular expressions.
For example.
import re
listy = ['1oo apples are bananas m20w', '2oo bananas are apples m20w', '3oo banapples are appnanas m20w']
number = input('Enter a number: ')
select = re.findall('{number} + 'oo(.+?)m20w', str(listy))
print('Did you know that' + str(select) + '?')
Enter a number:
Enter a number: 3
Did you know that [‘ banapples are appnanas ‘]?
With the goal being that if the user enters ‘3’ into the terminal, then that part of the list is printed out, rather than python generating a string that is identical to the list[n].
The purpose of using (.+?) is to find anything between the two limiters I have specified, without leaving out any aspect of it.
If I wanted to do this without user input, then the way I could achieve that would be:
import re
list = ['1oo apples are bananas'~, '2oo bananas are apples m20w', '3oo banapples are appnanas m20w']
select = re.findall('2oo(.+?)m20w', str(listy))
print('Did you know that' + str(select) + '?')
And having tested that, it does indeed spit out the second list element
Did you know the [‘ bananas are apples ‘]
The ‘oo’ and ‘m20w’ are just random string word soups used to help regex find unique list items. They serve no purpose besides being unique strings of text that a command like re.findall can easily find without getting stuck on other bits of the string.
The purpose of using regular expressions and user input over just having something like this:
number = input()
if str(number) == 1:
print("bananas are apples")
elif str(number) == 2:
print("apples are bananas")
else:
print("banapples and appnanas")
is so I can select aspects of lists I generate that have variable length, string concatenations and ranges. I would prefer to do it the simple way but it just doesn’t work for what I’m doing.
I have tried the first method to much disappointment. If someone could point me in the right direction to get the code to work in the way it’s intended to, then any help is appreciated, thank you.
>Solution :
Try changing the select assignment line like this:
select = re.findall(f'{number}oo(.+?)m20w', str(list))