字符串格式化
作业一:使用字符串格式化方法(%或format)定义个人信息
- 个人信息:本课程名+学号+姓名+年龄+好友名(任意或虚拟)
- 使用字符串内置函数对个人信息进行查找、分隔、插入、替换操作(方式不限)。
# 字符串格式化定义个人信息
str_my_need = '{class_name},{student_number},{name},{age},{friend_name}'.format(class_name = 'Python',\
student_number = 'f19266666', name = 'Jason系由', age = '18', friend_name = '派小森')
print('所定义的个人信息字符串是:{}'.format(str_my_need))
# 查找(姓名)
result_find = str_my_need.find('Jason系由')
print('所搜索的元素起始位置是:{}'.format(result_find))
# 分隔:按照','进行分隔
result_separate = str_my_need.split(',')
print('按照逗号分隔后的结果是:{}'.format(result_separate))
# 插入一个新的信息元素——年级
# 并以' ,作为连接符'
result_insert = ' ,'.join(['大一', str_my_need])
print('插入年级之后的结果是:{}'.format(result_insert))
# 字符串替换
result_replace = str_my_need.replace('派小森', '高小数')
print('替换后的结果是:{}'.format(result_replace))
面对对象
作业二:使用面向对象程序设计满足如下要求
- 设计一个打字准确率程序
- 要使用到封装、继承、多态
- 判定内容包括数字、字母(大小写)、字符、字符串
- 返回结果:屏幕打印对或错、对错的次数
- 可选:返回错误具体内容
import random
import string
class Self(object):
def __init__(self):
self.len = 10
#设置检测字符串的最大长度
# 定义父类
class Type(Self):
# 继承
def type(self, input_time):
while input_time:
print('还剩{:d}次输入'.format(input_time))
input_time -= 1
content_scope = string.printable
content = ''.join(random.sample(content_scope, random.randint(1, Self().len)))
# sample函数:从给定范围中取出指定数量的元素
# 随机生成字符串
print(content, '\t共%d个字符' % len(content))
your_input = input()
ipnut_list = list(your_input)
true_list = list(content)
if len(your_input) != len(true_list):
if len(your_input) > len(true_list):
print('多输入了{}位!!!'.format(len(your_input) - len(true_list)))
continue
else:
print('少输入了{}位!!!'.format(len(true_list) - len(your_input)))
continue
for i in range(0, len(content)):
if ipnut_list[i] == true_list[i]:
if i == Self().len - 1:
print("全部正确!")
break
elif ipnut_list[i] == '' and true_list[i] != '':
print('少输入{}位'.format(len(content)))
break
else:
print("错误:第{}处的{}".format(i + 1, true_list[i]))
n = int(input("请输入你想输入的次数:"))
print('输入的次数共{}次'.format(n))
# 确认用户输入次数
demo_type = Type()
demo_type.type(n)