在Python中生成随机字母 [英] Generate a random letter in Python

查看:519
本文介绍了在Python中生成随机字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在Python中生成随机字母(如random.randint,但用于字母)? random.randint的范围功能会很好,但是拥有只输出随机字母的生成器总比没有好.

Is there a way to generate random letters in Python (like random.randint but for letters)? The range functionality of random.randint would be nice but having a generator that just outputs a random letter would be better than nothing.

推荐答案

简单:

>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> import random
>>> random.choice(string.ascii_letters)
'j'

string.ascii_letters 返回包含小写字母的字符串以及根据当前语言环境的大写字母.

string.ascii_letters returns a string containing the lower case and upper case letters according to the current locale.

random.choice 从序列中返回单个随机元素

random.choice returns a single, random element from a sequence.

这篇关于在Python中生成随机字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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