python - 从 [A-z] 生成飞行字符串

标签 python random

我想知道最简单的编写方法的方法是生成从 1 到 50 的数字,然后根据生成的数字返回字符串,如下所示:

Abcdef 如果生成的数字是 6
Abcdefghi 如果生成的数字是 9。

我正在使用 python 3.2

最佳答案

有几种方法,最简单的:

>>> import string
>>> import random
>>> string.ascii_letters[:random.randint(1, 50)].title()
'Abcdefghijklmnopq'
>>> string.ascii_letters[:random.randint(1, 50)].title()
'Abcdefghijklmnopqrstuvwxyzabcdefghijklmnopq'
>>> string.ascii_letters[:random.randint(1, 50)].title()
'Abcdefghijklmnopqrs'    

或者你可以试试 itertools:

>>> import string
>>> import random
>>> from itertools import islice, cycle
>>> def randstr():
...     return ''.join(islice(cycle(string.ascii_lowercase),
...                           random.randint(1, 50))).title()
...
>>> randstr()
'Abcdefghijklmnopq'
>>> randstr()
'Abcdefghijklmnopqrstuvwxyzabcdefghijklmnopq'
>>> randstr()
'Abcdefghijklmnopqrs'    

关于python - 从 [A-z] 生成飞行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6174827/

相关文章:

Python - Pandas - DataFrame 减少行数

python - 我不知道如何让我的 Plotly 图表只显示整数

php - 添加类别内的相关游戏

python - 按随机顺序做事?

python - 不会为自定义用户模型保存配置文件数据

python - Django-不支持的操作数类型/: 'dict' and 'dict'

python - 如何在 NetworkX 或 igraph 中使用多部分图?

javascript - 是什么会导致Math.random()在每次重新加载页面时生成相同的 “random”号?

asp.net - 我应该在哪里存储百万条记录的数组?

Ruby - 以随机顺序返回一个数组