实验2 字符串和列表


# 使用字符串的format()方法,对输出数据项进行格式化 x1, y1
=1.2, 3.57 x2, y2 =2.26, 8.7 # 输出1 print('{:-^40}'.format(x1, y1)) # {:-^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)) 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))

 

总结:format()能够对字符串做出各种格式化操作,可以通过设置关键字参数来指定位置;可以用来实现填充和对齐;可以实现不同精度和类型的设置;也可以用来实现不同进制的输出

x = input('输入一个字符串:')
x = x.upper()
x = x.replace('A','')
print(x)

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

 

 

x="""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!"""
a = len(x.splitlines())
b = len(x.split())
c = 0
for i in x:
if i == ' ':
c = c + 1
d = len(x)
print(f'行数:{a}')
print(f'单词数:{b}')
print(f'字符数:{d}')
print(f'空格数:{c}')

 

 

 

x = input('最想实现的心愿1:')
y = input('最想实现的愿望2:')
z = input('最想实现的愿望3:')
print('{:-^50}'.format('我的愿望清单'))
print(f'{1}.{x}')
print(f'{2}.{y}')
print(f'{3}.{z}')

 

 

实验总结:

1.收获:

   理解了字符串在程序设计中的作用并了解了字符串的常见操作

2.体会和问题:

  熟练掌握字符串的操作和数据结构类型对于一些文本的处理非常方便,而且处理大量数据也变得更加容易。但在一些实际问题上,如何将已学的操作组合使用起来,如何使得编写的程序更加简单,还略有不足,不能熟练使用一些函数和操作。

 

posted @ 2021-04-02 21:07  申富明  阅读(201)  评论(3)    收藏  举报