实验二
# 使用字符串的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}, y2 = {:.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中对字符串(str)使用format()方法可以实现左对齐,右对齐,居中显示,指定某字符用以补白的精细操作(有点儿类似于word),值得注意的是{':-^40'.format(s)}中“-”,“^”和“40”的顺序进行调换是不能正常运行的,也可以通过(‘{:[0:2]}’.format(s))实现对字符串的选择性提取,亦可以通过('{:.1f}'.format(s))实现对小数位数的控制,综合几种format()用法即可实现各种对字符串的精细控制。
info = input('输入一串字符:') info = info.upper() info = info.replace('A', '') print(info)

# 把姓名转换成大写,遍历输出 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'] n = 0 name_list.sort() for name in name_list: x = name.title() n += 1 print(f'{n}.{x}')

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! ''' hang = len(text.splitlines()) word_num = len(text.split()) zifu = len(text) blank = 0 for i in text: if i == ' ': blank += 1 print(f'行数:{hang}') print(f'单词数:{word_num}') print(f'字符数:{zifu}') print(f'空格数:{blank}')

x = 0 y = 0 list1 = [] word = '我的愿望清单' while x < 3: info = input('输入想要加入愿望清单的事情:') list1.append(info) x += 1 print('{:-^50}'.format(word)) for i in list1: y += 1 print(f' {y}.{i}')

实验总结:
通过这次对字符串由浅入’深‘的几个小练习,我学会了几种对字符串的简单处理。与此同时,我也发现Python实现各种功能的本质就是对数据的录入、识别、修改、机内再录入、机内再识别、机内再修改……在输入数据后,数据在计算机中通过python解释器不断地运算处理加工,通过计算机对原始数据一点一滴地“微调加工”,无数次的累计,才输出了结果。我们“小码农”要做的就是把目标细分,先完成一部分,再完成一部分,就像我们的python学习一样不能一蹴而就,学无止境,只有一点一滴的积累才能得到我们想要的结果。

浙公网安备 33010602011771号