首页 > 其他分享 >实验2

实验2

时间:2023-04-01 19:22:35浏览次数:39  
标签:10 list len 列表 字符串 实验 print

实验目的

1. 知道Python中字符串的表示,熟练使用索引、切片、常见字符串操作
2. 知道Python中列表的表示,熟练使用索引、切片、常见列表操作,能正确使用列表推导式
3. 针对具体问题场景,能够灵活、组合使用字符串、列表、控制语句编程解决实际问题

实验准备

实验前,请练习/复习以下内容:
4. Python中字符串表示的三种方式;对字符串的索引、切片操作;字符串常用方法
5. Python中列表的表示;对列表的索引、切片操作;列表常用方法
6. 控制语句while的基础用法
实验内容
1. 实验任务1
在python开发环境下,新建一个.py源文件,输入并运行以下代码。结合运行结果和注释,体验这里用到的
字符串方法。
task1.py

 1 # 字符串的基础操作
 2 # 课堂上没有演示的一些方法
 3 
 4 x = 'nba FIFA'
 5 print(x.upper()) # 字符串转大写
 6 print(x.lower()) # 字符串转小写
 7 print(x.swapcase()) # 字符串大小写翻转
 8 print()
 9 
10 x = 'abc'
11 print(x.center(10, '*')) # 字符串居中,宽度10列,不足左右补*号
12 print(x.ljust(10, '*')) # 字符串居左,宽度10列,不足右边补*号
13 print(x.rjust(10, '*')) # 字符串居右,宽度10列,不足左边补*号
14 print()
15 
16 x = '123'
17 print(x.zfill(10)) # 字符串宽度10列,不足左边用0填充
18 x = 123
19 print(str(x).zfill(10)) # 把int类型转换成字符串类型后,对字符串对象使用str.zfill()方法
20 print()
21 
22 x = 'phone_number'
23 print(x.isidentifier()) # 判断字符串是否是python合法标识符
24 x = '222test'
25 print(x.isidentifier())
26 print()
27 
28 x = ' '
29 print(x.isspace()) # 判断字符串是否是空白符(包括空格、回车、Tab键)
30 x = '\n'
31 print(x.isspace())
32 print()
33 
34 x = 'python is fun'
35 table = x.maketrans('thon', '1234') # 为字符串对象x创建一个字符映射表, 字符thon分别映射到字符1234
36 print(x.translate(table)) # 根据字符映射表table对字符串对象x中的字符进行转换

运行结果

试验任务2

在Python开发环境下,输入并运行以下python代码。结合运行结果和注释,理解、复习这个简单练习中用
到的字符串、列表、格式化,以及使用while循环遍历列表的操作。
task2.py

 1 # 基础练习: 列表、格式化、类型转换
 2 
 3 x = [5, 11, 9, 7, 42]
 4 
 5 print('整数输出1: ', end = '')
 6 i = 0
 7 while i < len(x):
 8       print(x[i], end = ' ')
 9       i += 1
10 
11 
12 print('\n整数输出2: ', end = '')
13 i = 0
14 while i < len(x):
15       print(f'{x[i]:02d}', end = '-') # 指定每个整数宽度占2列;不足2列,左边补0
16       i += 1
17 
18 
19 print('\n整数输出3: ', end = '')
20 i = 0
21 while i < len(x) - 1:
22       print(f'{x[i]:02d}', end = '-')
23       i += 1
24 print(f'{x[-1]:02d}')
25 
26 
27 print('\n字符输出1: ', end = '')
28 y1 = []
29 i = 0
30 while i < len(x):
31       y1.append(str(x[i])) # 函数str()用于把其它类型对象转换成字符串对象
32       i += 1
33 print('-'.join(y1))
34 print('字符输出2: ', end = '')
35 y2 = []
36 i = 0
37 while i < len(x):
38     y2.append( str(x[i]).zfill(2) ) # x[i]是int类型对象,使用str()转换成字符串对象后,处理,然后加入到列表y中
39 i += 1
40 print('-'.join(y2))

运行结果

试验任务2

在python开发环境下,输入如下代码。结合运行结果,理解、复习这个代码示例中的以下操作:
通过while语句遍历列表
字符串方法 .title() 和 .join() 用法
task3.py

实验任务4

设英文姓名信息存储在列表中:name_list = ['david bowie', 'louis armstrong', 'leonard cohen', 'bob dylan', 'cocteautwins']

编写python程序task4.py,将姓和名首字母转换成大写,将姓名按字典序编号输出。
程序正确编写后,预期结果如下:

1 name_list = ['david bowie', 'louis armstrong', 'leonard cohen', 'bobdylan','cocteautwins']
2 change = [i.title() for i in name_list]
3 for i, item in enumerate(sorted(change)):
4     print((i + 1), '.', item)

运行结果

实验任务5

 

 1 chat = '''The Zen of Python, by Tim Peters
 2 
 3 Beautiful is better than ugly.
 4 Explicit is better than implicit.
 5 Simple is better than complex.
 6 Complex is better than complicated.
 7 Flat is better than nested.
 8 Sparse is better than dense.
 9 Readability counts.
10 Special cases aren't special enough to break the rules.
11 Although practicality beats purity.
12 Errors should never pass silently.
13 Unless explicitly silenced.
14 In the face of ambiguity, refuse the temptation to guess.
15 There should be one-- and preferably only one --obvious way to do it.
16 Although that way may not be obvious at first unless you're Dutch.
17 Now is better than never.
18 Although never is often better than *right* now.
19 If the implementation is hard to explain, it's a bad idea.
20 If the implementation is easy to explain, it may be a good idea.
21 Namespaces are one honking great idea -- let's do more of those!'''
22 print('行数:',len(chat.splitlines()))
23 print('单词数:',len(chat.split()))
24 print('字符数:',len(chat))
25 print('空格数:',chat.count(' '))

运行结果

实验6

 1 book_list = [['静静的顿河','肖洛霍夫','金人', '人民文学出版社'],
 2 ['大地之上','罗欣顿.米斯特里','张亦琦', '天地出版社'],
 3 ['夜航西飞', '柏瑞尔.马卡姆', '陶立夏', '人民文学出版社'],
 4 ['来自民间的叛逆', '袁越', '','新星出版社'],
 5 ['科技与恶的距离', '珍妮.克里曼', ' 詹蕎語', '墨刻出版社'],
 6 ['灯塔','克里斯多夫.夏布特','吕俊君','北京联合出版公司'],
 7 ['小行星掉在下午','沈大成', '', '广西师范大学出版社']]
 8 
 9 print('{:*^40}'.format('图书信息'))
10 for i in range(len(book_list)):
11    print(f"{i+1}.《{book_list[i][0]}》 |{book_list[i]

运行结果

实验任务7

 1 data = ['99 81 75', '30 42 90 87', '69 50 96 77 89 93', '82 99 78 100']
 2 
 3 sum = 0
 4 count = 0
 5 for i in data:
 6   x = i.split()
 7 for n in x:
 8   sum += int(n)
 9 count += 1
10 
11 y = eval('sum / count')
12 print(f'{y:.2f}')

运行结果

实验任务8

1 words_sensitive_list = ['张三', 'V字仇杀队', '杀']
2 comments_list = ['张三因生命受到威胁正当防卫导致过失杀人,经辩护律师努力,张三不需负刑事责任。',
3                  '电影<V字仇杀队>从豆瓣下架了', '娱乐至死']
4 
5 for comment in comments_list:
6     for word in words_sensitive_list:
7         if word in comment:
8             comment = comment.replace(word, '*' * len(word))
9     print(comment)

运行结果

实验任务9

 1 # 家用电器销售系统
 2 # v1.2
 3 
 4 # 欢迎信息
 5 print('欢迎使用家用电器销售系统!')
 6 
 7 # 产品信息列表
 8 products = [
 9     {'编号': '0001', '名称': '电视机', '品牌': '海尔', '价格': 5999.00, '库存数量': 20},
10     {'编号': '0002', '名称': '冰箱', '品牌': '西门子', '价格': 6998.00, '库存数量': 15},
11     {'编号': '0003', '名称': '洗衣机', '品牌': '小天鹅', '价格': 1999.00, '库存数量': 10},
12     {'编号': '0004', '名称': '空调', '品牌': '格力', '价格': 3900.00, '库存数量': 0},
13     {'编号': '0005', '名称': '热水器', '品牌': '美的', '价格': 688.00, '库存数量': 30},
14     {'编号': '0006', '名称': '笔记本', '品牌': '联想', '价格': 5699.00, '库存数量': 10},
15     {'编号': '0007', '名称': '微波炉', '品牌': '苏泊尔', '价格': 480.50, '库存数量': 33},
16     {'编号': '0008', '名称': '投影仪', '品牌': '松下', '价格': 1250.00, '库存数量': 12},
17     {'编号': '0009', '名称': '吸尘器', '品牌': '飞利浦', '价格': 999.00, '库存数量': 9},
18 ]
19 
20 # 产品信息列表表头
21 header = '{:<10}{:<10}{:<10}{:<10}{:<10}'.format('编号', '名称', '品牌', '价格', '库存数量')
22 print('产品和价格信息如下:')
23 print('*****************************************************')
24 print(header)
25 print('--------------------------------------------------------')
26 
27 # 打印商品信息
28 for product in products:
29     row = '{:<10}{:<10}{:<10}{:<10.2f}{:<10}'.format(
30         product['编号'], product['名称'], product['品牌'], product['价格'], product['库存数量'])
31     print(row)
32 
33 # 用户输入信息
34 product_id = input('请输入您要购买的产品编号:')
35 count = int(input('请输入您要购买的产品数量:'))
36 
37 # 获取编号对应商品的信息
38 product_index = int(product_id) - 1
39 product = products[product_index]
40 
41 # 计算金额
42 total_price = product['价格'] * count
43 print(f'购买成功,您需要支付{total_price:.2f}元')
44 
45 # 退出系统
46 print('谢谢您的光临,下次再见!')

运行结果9

 





标签:10,list,len,列表,字符串,实验,print
From: https://www.cnblogs.com/emcr/p/17242948.html

相关文章

  • 实验2
    实验任务一源代码#include<stdio.h>#include<stdlib.h>#include<time.h>#defineN5#defineR1586#defineR2701intmain(){intnumber;inti;srand(time(0));for(i=0;i<N;++i){number=rand()%(R2......
  • 202031607323-后涌- 实验一 软件工程准备—什么是软件?什么是工程?
    项目内容班级博客链接班级链接本次作业要求链接作业要求我的课程学习目标了解掌握软件在开发过程中的过程、方法和工具本次作业在哪些方面帮我实现学习目标准备学习软件工程的工具任务1:调查问卷在以下网址提交课程调查问卷完成情况:已认真填写并提......
  • 实验三
    task1.c#include<stdio.h>#include<stdlib.h>#include<time.h>#include<windows.h>#defineN80voidprint_text(intline,intcol,chartext[]);//函数声明voidprint_spaces(intn);voidprint_blank_lines(intn);intmain(){i......
  • 实验3
    实验任务1源代码#include<stdio.h>#include<stdlib.h>#include<time.h>#include<windows.h>#defineN80voidprint_text(intline,intcol,chartext[]);voidprint_spaces(intn);voidprint_blank_lines(intn);intmain(){......
  • 实验三
    试验任务一源码程序#include<stdio.h>#include<stdlib.h>#include<time.h>#include<windows.h>#defineN80voidprint_text(intline,intcol,chartext[]);//函数声明voidprint_spaces(intn);//函数声明voidprint_blank_lines(intn);/......
  • 202031607224-邓思超 实验一 软件工程准备—认识软件工程
    实验一软件工程准备项目内容班级博客链接班级博客本次作业要求链接本次作业要求链接我的课程学习目标(1)学习博客园软件开发者学习社区使用技巧和经验。(2)了解Github的基本操作。本次作业在哪些方面帮我实现学习目标(1)通过博客园阅读了专业相关的一些博客内容......
  • 实验3
    试验任务1#include<stdio.h>#include<time.h>#include<windows.h>#defineN80voidprint_text(intline,intcol,chartext[]);//函数声明voidprint_spaces(intn);//函数声明voidprint_blank_lines(intn);//函数声明intmain(){intline,......
  • linux操作系统实验四-以time/gettimeofday系统调用为例分析ARM64 Linux 5.4.34
    一、搭配环境(1)安装编译工具sudoapt-getinstallgcc-aarch64-linux-gnusudoapt-getinstalllibncurses5-dev build-essentialgitbisonflexlibssl-dev(2)制作根文件系统wget https://busybox.net/downloads/busybox-1.33.1.tar.bz2tar-xjfbusybox-1.33.1.tar.bz2......
  • 实验3 函数应用编程
      task1#include<stdio.h>#include<stdlib.h>#include<time.h>#include<windows.h>#defineN80voidprintf_text(intline,intcol,chartext[]);voidprintf_spaces(intn);voidprintf_blank_lines(intn);intmain(){intlin......
  • 实验3
    任务1:#include<stdio.h>#include<stdlib.h>#include<time.h>#include<windows.h>#defineN80voidprint_text(intline,intcol,chartext[]);//函数声明voidprint_spaces(intn);//函数声明voidprint_blank_lines(intn);//函数声明intmain(){......