Generate list from user input

家住魔仙堡 提交于 2020-02-08 06:24:49

问题


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 Blah 30 Blah',
]

回答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 in range(start, end + 1)]

>>> pprint(my_list)
['Blah Blah 1 Blah',
 'Blah Blah 2 Blah',
 ...
 'Blah Blah 29 Blah',
 'Blah Blah 30 Blah']



回答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!




回答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))


来源:https://stackoverflow.com/questions/41212721/generate-list-from-user-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!