从用户输入生成列表

Generate list from user input

我如何让用户输入类似 Blah Blah [1-30] Blah 的内容,然后解析它以获得如下列表:

[
    'Blah Blah 1 Blah',
    'Blah Blah 2 Blah',
    etc...
    'Blah Blah 30 Blah',
]

根据您的需要编辑:

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

使用正则表达式。首先找到起点和终点,由[a-b]指定。然后循环它们,并用递增的数字替换这些括号:

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']

如果您不想使用正则表达式,您可以尝试使用 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)

试一试here!