- 学习测试开发的Day79,真棒!
- 学习时间为1H05M
- 第八次全天课(上午视频40M-1H20M)
练习3:生成随机的字母和数字,需要类似格式:字母数字字母数字字母数字,生成长度为10的字符串
自己的
代码
import random
result1=[]
for i in range(1,11):
if i%2==0:
result1.append(random.randint(0,9))
else:
result1.append(chr(random.randint(65,90)))
s=""
for i in result1:
s+=str(i)
print(s)
输出结果
PS D:\0grory\day8> python .\randomtest.py
D9Y4M0E5W1
PS D:\0grory\day8>
老师
输入---->存储----->计算(存储)--->输出
方法1代码:
import random
result=""
for i in range(5):
result+=chr(random.randint(97,122))+str(random.randint(0,9))
print(result)
输出结果:
PS D:\0grory\day8> python .\randomtest.py
s2n3f0s6i1
PS D:\0grory\day8>
方法2:
import random
result=""
for i in range(1,11):
if i%2==0:
result+=str(random.randint(0,9))
else:
result+=chr(random.randint(97,122))
print(result)
输出结果
PS D:\0grory\day8> python .\randomtest.py
j8a4d4i9w4
PS D:\0grory\day8>
方法三代码:
import random
import string
result=""
for i in range(5):
result+=string.ascii_letters[random.randint(0,52)]+string.digits[random.randint(0,9)]
print(result)
结果:
PS D:\0grory\day8> python .\randomtest.py
k6t2B4V1a0
PS D:\0grory\day8>
练习4:生成随机的字母和数字,需要类似格式:用函数实现且生成的字符串长度,可以通过函数参数来指定
自己的代码:
import random
import string
def myrandom(num):
result=""
for i in range(num):
result+=string.ascii_letters[random.randint(0,52)]+string.digits[random.randint(0,9)]
return result
num=int(input("请输入你想生成的字符串长度:"))
print(myrandom(num))
输出:
请输入你想生成的字符串长度:9
t8Q6L9C8a3A6w2M9d8
老师建议-且字母为指定范围内:
import random
import string
def gen_random_str(length,a,b):
result=""
if not (isinstance(length,int) and (isinstance(a,int) and (isinstance(b,int)))and length>0 and a>=97 and a<=122):
return ""
for i in range(1,length+1):
if i%2==0:
result+=str(random.randint(0,9))
else:
result+=chr(random.randint(97,122))
return result
length=int(input("请输入你想生成的字符串长度:"))
print(gen_random_str(length,97,100))
结果:
PS D:\0grory\day8> python .\randomtest.py
请输入你想生成的字符串长度:10
a7w4r4o8r1
练习5:统计一句话的单词数量
例如: I am a 18 years old boy ! Do you believe , do you?
提示:
1.想办法把标点和数字给过滤掉(用列表,用新的字符串进行拼接)
2.split
3.len(长度)
自己的:
代码
import string
print(string.ascii_letters)
s="I am a 18 years old boy ! Do you believe , do you?"
s2=""
for i in s:
if (i>='a' and i<='z') or (i>='A' and i<='Z'):
s2+=i
elif i==" ":
s2+=i
else:
i=""
print(s2)
s3=s2.split()
print(len(s3))
输出结果:
PS D:\0grory\day8> python .\word_num.py
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
I am a years old boy Do you believe do you
11
PS D:\0grory\day8>