根据用户输入生成列表 [英] Generate list from user input

查看:64
本文介绍了根据用户输入生成列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

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

这篇关于根据用户输入生成列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆