实验二
一.实验内容
实验任务一.
在Python开发环境下,输入并运行以下python代码。结合注释和运行结果,理解使用字符串的format() 方法对数据输出格式的精细控制。
# 使用字符串的format()方法,对输出数据项进行格式化 x1, y1 = 1.2, 3.57 x2, y2 = 2.26, 8.7 # 输出1 #print('{:-^40}'.format('输出1')) # {:-^40}控制输出数据格式: 宽度占40列,居中对齐,空白处用-补齐 print('x1 = {}, y1 = {}'.format(x1, y1)) print('x2 = {}, y2 = {}'.format(x2, y2)) # 输出2 #print('{:-^40}'.format('输出2')) # {:-^40}控制输出数据格式: 宽度占40列,居中对齐,空白处用-补齐 print('x1 = {:.1f}, y1 = {:.1f}'.format(x1, y1)) # {:.1f}控制小数输出精度,保留1位小数 print('x2 = {:.1f}, y2 = {:.1f}'.format(x2, y2)) # 输出3 #print('{:-^40}'.format('输出3')) # {:-^40} 控制输出数据格式: 宽度占40列,居中对齐,空白处用-补齐 print('x1 = {:<15}, y1 = {:<15}'.format(x1, y1)) # {:<15}控制数据输出宽度占15列,左对齐,空白处默认补空格 print('x2 = {:<15}, y2 = {:<15}'.format(x2, y2))
实验任务二.
编写一个Python程序,实现如下要求: 提示用户输入一个字符串,将用户输入字符串中的所有字符变成大写,并去掉其中的A字符,并在屏幕 上打印输出。 预期运行测试结果如下: 用户输入:what a beautiful spring day 屏幕输出:WHT BEUTIFUL SPRING DY
x=input('enter a str:') s=x.upper() y=s.replace('A','') print(y)
实验任务三.
在python开发环境下,输入如下程序。观察运行结果,理解这个代码示例中的以下操作:
通过for语句遍历列表
使用字符串处理方法s.title()
实现英文姓和名首字母大写
使用print()函数实现按编号输出姓名
# 把姓名转换成大写,遍历输出 name_list = ['david bowie', 'louis armstrong', 'leonard cohen', 'bob dylan','cocteau twins'] n = 1 for name in name_list: print(f'{n}: {name.title()}') n+=1
实验任务四.
设英文姓名信息存储在列表中: name_list = ['david bowie', 'louis armstrong', 'leonard cohen', 'bob dylan', 'cocteau twins'] 编写python程序,将姓和名首字母转换成大写,按字典序编号输出。
name_list = ['david bowie',"louis armstrong","leonard cohen","bob dylan","cocteau twins"] name_list2 = sorted(name_list) n=1 for name in name_list2: print(f'{n}.{name.title()}') n+=1
实验任务五.
编程统计Zen Of Python(Python之禅)的行数、单词数、字符数、空格数。
text=''' The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! ''' print('行数:',len(text.splitlines())) print('单词数:',len(text.split())) print('字符数:',len(text)) print('空格数:',text.count(' '))
实验任务六.
编写一个Python程序,实现如下要求: 输入3个最想实现的心愿加入愿望清单列表。然后,将愿望清单中的内容编号后逐条打印出来。 逐条打印前,打印出标题行'我的愿望清单',居中,宽度占50列,左右以短线-填充。
u = [] i = 0 while i<3: x = input("输入想要加入愿望清单的事情:") u.append(x) i+=1 print('{:-^50}'.format("我的愿望清单")) n = 1 for d in u: print(f'{" "}{n}.{d}') n+=1
二.实验总结
我掌握了Python中字符串以及列表的表示、索引和切片,以及常用操作 , 能够灵活运用字符串、列表编程解决现实世界的应用问题。