鱼C论坛

 找回密码
 立即注册
查看: 2308|回复: 7

[已解决]python随机字母

[复制链接]
发表于 2020-5-26 15:51:54 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
如何在python里写一个从26个字母随机挑几个字母的程序
我知道要用random,可不知道具体怎么办
最佳答案
2020-5-26 16:04:15
用 ASCII 转化  因为我们知道 大写的A ASCII码为65  Z为90 只要随机抽取这些数字即可:
  1. from random import randint
  2. number = int(input('请输入你要随机抽取几个字母?'))
  3. letter = ''
  4. while number:
  5.     letter+=(chr(randint(65,90)))
  6.     number -= 1
  7. print(letter)
复制代码

小写的:
  1. from random import randint
  2. number = int(input('请输入你要随机抽取几个字母?'))
  3. letter = ''
  4. while number:
  5.     letter+=(chr(randint(97,122)))
  6.     number -= 1
  7. print(letter)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-5-26 15:53:47 | 显示全部楼层
要大写 要小写? 还是都要哈哈
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-5-26 15:57:37 | 显示全部楼层
  1. >>> from string import ascii_lowercase
  2. >>> ascii_lowercase
  3. 'abcdefghijklmnopqrstuvwxyz'
  4. >>> from random import choice
  5. >>> for i in range(10):
  6.         print(choice(ascii_lowercase))

  7.        
  8. d
  9. b
  10. l
  11. e
  12. c
  13. o
  14. g
  15. m
  16. x
  17. z
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-5-26 15:58:01 | 显示全部楼层
random.choice,可以用列表随机生成。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-5-26 16:04:15 | 显示全部楼层    本楼为最佳答案   
用 ASCII 转化  因为我们知道 大写的A ASCII码为65  Z为90 只要随机抽取这些数字即可:
  1. from random import randint
  2. number = int(input('请输入你要随机抽取几个字母?'))
  3. letter = ''
  4. while number:
  5.     letter+=(chr(randint(65,90)))
  6.     number -= 1
  7. print(letter)
复制代码

小写的:
  1. from random import randint
  2. number = int(input('请输入你要随机抽取几个字母?'))
  3. letter = ''
  4. while number:
  5.     letter+=(chr(randint(97,122)))
  6.     number -= 1
  7. print(letter)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-5-26 16:06:32 | 显示全部楼层
  1. import random
  2. num_lower=chr(random.randint(65,90) )
  3. num_upper=chr(random.randint(97,122) )
  4. print(num_lower,num_upper)
复制代码


以上,程序运行一次随机大小写变一次。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-5-26 16:19:59 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-5-27 10:16:44 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-29 15:57

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表