加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 23:01:15 所属栏目:Python 来源:网络整理
导读:我想知道什么是最简单的方法来编写从1到50生成数字的方法,然后依赖于生成的数字返回我的字符串如: Abcdef如果生成的数字是6 Abcdefghi如果生成的数字是9. 我正在使用python 3.2 解决方法 有几种方法,最简单的方法: import string import random string.asc
我想知道什么是最简单的方法来编写从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'

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读