实验目的
- 了解转义字符和原始字符串的概念和用法
- 熟练运用字符串常用方法
- 熟练运用运算符和内置函数对字符串的操作
实验内容
- 随机密码生成。编写程序,在26个字母大小写和10个数字组成的列表中随机生成10个8位密码。(提示:可使用随机函数choice())
- 输一个英文句子,将其中的小写字母转换为大写字母后并输出。
- 输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数。
实验过程
- 随机密码生成。编写程序,在26个字母大小写和10个数字组成的列表中随机生成10个8位密码。(提示:可使用随机函数choice())
第一种解法
程序代码如下
import random
pass_select = [] #定义一个列表来存放26个大小写字母和10个数字
for j in [chr(x) for x in range(ord('a'),ord('z')+1)]: #先将小写字母循环添加到列表中
pass_select.append(j)
for j in [chr(x) for x in range(ord('A'),ord('Z')+1) ]: #将大写字母循环添加到列表中
pass_select.append(j)
for j in [x for x in range(0,10)]: #随机在0-9之间生成10个数字,也可以改为range(10)
pass_select.append(str(j))
#print(pass_select)
for i in range(10): #随机生成10个密码
password1 = ''
for j in range(8): #在列表中随机提取8位出来组成密码
password1 += random.choice(pass_select)
print(password1)
运行截图如下
第二种解法
程序代码如下
from random import choice
import string
def password():
length = 8
chars = string.ascii_letters + string.digits
return "".join((choice(chars) for i in range(8)))
for i in range(10):
print(password())
运行截图如下
- 输一个英文句子,将其中的小写字母转换为大写字母后并输出。
第一种解法
程序代码如下
test = input('请输入一个英文句子:')
for eng in test:
if 97 <= ord(eng) <=122:
upper_eng = ord(eng) - 32
print(chr(upper_eng),end = '')
else:
print(eng,end = '')
运行截图如下
第二种解法
程序代码如下
s1 = input('请输入英文句子:')
s2 = s1.upper()
print(s2)
运行截图如下
- 输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数。
程序代码如下
import string
test = input('please input a string:')
letters = 0
space = 0
digit = 0
others = 0
for sort in test:
if sort.isalpha():
letters += 1
elif sort.isspace():
space += 1
elif sort.isdigit():
digit += 1
else:
others += 1
print('该行字符的统计结果如下:\n中英文字母的个数为{}\n空格的个数为{}\n数字的个数为{}\n其他字符的个数为{}'.format(letters,space,digit,others))
运行截图如下