在python上获得随机字符
2023-09-27 14:27:48 时间
"""今天写一个程序,在想既然可以获得随机数,那我可不可以获得任意字符呢,于是在stackoverflow.com 上找到了方法,几乎都是导入random模块,然后再用其它方法间接实现。
现在总结如下:""" #获取单个字符 >>> import random >>> import string >>> random.choice(string.ascii_lowercase) 'b' >>> import string >>> string.letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> import random >>> random.choice(string.letters) 'j' import random def guess_letter(): return random.choice('abcdefghijklmnopqrstuvwxyz') import string #This was a design above but failed to print. I remodled it. import random irandom = random.choice(string.ascii_letters) print irandom #获取固定长度的随机字符: >>>def random_char(y): return ''.join(random.choice(string.ascii_letters) for x in range(y)) >>>print (random_char(5)) >>>fxkea
可以简化为:''.join(random.sample(string.ascii_lowercase,5))
# 获取固定长度,随机混合的数和随机字母
import string import random
KEY_LEN = 20 def base_str(): return (string.letters+string.digits) def key_gen(): keylist = [random.choice(base_str()) for i in range(KEY_LEN)] return ("".join(keylist)) You can get random strings like this: g9CtUljUWD9wtk1z07iF ndPbI1DDn6UvHSQoDMtd klMFY3pTYNVWsNJ6cs34 Qgr7OEalfhXllcFDGh2l
相关文章
- 【阿玥教程】Python条件语句的详细讲解
- 【Python开发】Url中文字符时记得转码edcode("utf-8")
- 【Python开发】Python中的class继承
- python 打印Linux中文编码字符
- Python编程笔记二进制、字符编码、数据类型
- 同花顺自选和雪球同步--测试 python 实现
- 第91天:Python matplotlib introduction
- python:斐波那契数列的计算!
- 怎么学习Python语言获得一技之长?
- 【Python】《大话设计模式》Python版代码实现
- python列表中的值转换为字符串,及列表(数组)里的所有值拼接成一个字符串 的方法(含字符变成数组的方法)
- python 爬虫系列03--职位爬虫
- 【Python基础】列表的基本操作:列表的数据统计、排序、遍历 || 关键字、函数、方法 || 列表的应用场景 || 元组的定义、循环遍历、应用场景 || 格式化字符 || 元组和列表之间的转换
- C++ 调用Python(Pyc文件)
- Python 图片转简单字符画
- Python的装饰器
- Python 自动化办公
- 程序媛过中秋的正确打开方式——使用Python绘制月饼消消乐,素描图,词云图,字符画图及提取轮廓
- python 中带有中文字符的字典打印log
- python批量重命名【截取文件名前六个字符 】
- 第11.6节 Python正则表达式的字符串开头匹配模式及元字符“^”(插入符、脱字符)功能介绍
- Python中文文件处理中涉及的字符编码及字符集
- Python中splitlines方法判断文本中一行结束除了回车换行符是否还有其他字符?
- Python判断字符类型
- Python 替换每个单词中的第一个字符的方法及示例代码
- Python 去除列表中重复的元素
- python class对象转换成json/字典