Generate List From User Input
How could I have a user input something like Blah Blah [1-30] Blah and then parse it to get a list like so: [ 'Blah Blah 1 Blah', 'Blah Blah 2 Blah', etc... 'Blah B
Solution 1:
Use regex. First find the start and end points ,specified by [a-b]
. Then loop them, and replace these brackets by the increasing number:
import re
expr = input('Enter expression: ') # Blah Blah [1-30] Blah
start, end = map(int, re.findall('(\d+)-(\d+)', expr)[0])
my_list = [re.sub('\[.*\]', str(i), expr) for i inrange(start, end + 1)]
>>> pprint(my_list)
['Blah Blah 1 Blah',
'Blah Blah 2 Blah',
...
'Blah Blah 29 Blah',
'Blah Blah 30 Blah']
Solution 2:
If you do not want to use regex you could try something like this using split:
user_input = input('Please enter your input e.g. blah blah [1-30] blah:')
list_definiton = (user_input[user_input.find('[')+len(']'):user_input.rfind(']')])
minimum = int(list_definiton.split('-')[0])
maximum = int(list_definiton.split('-')[1])
core_string = user_input.split('[' + list_definiton + ']')
string_list = []
for number in range(minimum, maximum + 1):
string_list.append("%s%d%s" % (core_string[0], number, core_string[1]))
print(string_list)
Try it here!
Solution 3:
Edited to your needs:
import re
seqre = re.compile("\[(\d+)-(\d+)\]")
s = "Blah Blah [1-30] blah"
seq = re.findall(seqre, s)[0]
start, end = int(seq[0]), int(seq[1])
l = []
for i in range(start, end+1):
l.append(re.sub(seqre, str(i), s))
Post a Comment for "Generate List From User Input"