Python自学笔记12:实操案例九(统计字符串中出现指定字符的次数、格式化输出商品的名称和单价)
1.统计字符串中出现指定字符的次数
写一个函数,传入字符串和要找的字符,调用,遍历字符串,返回计数结果,用print输出即可。


def get_count(s,ch):#s是字符串,ch是要查找的字符
count=0
for item in s:
if ch.upper()==item or ch.lower()==item:#大写或者小写匹配
count=1
return count
if __name__=='__main__':
s='hellopython,hellojava,hellogp'
ch=input('请输入要统计的字符:')
count=get_count(s,ch)
print(f'{ch}在{s}中出现的次数为:{count}')
2.格式化输出商品的名称和单价

增添字符串长度以后,对不齐的地方就把标题栏加空格或者制表符手动对齐就行了:
def show(lst):
for item in lst:
for i in item:
print(i, end='\t\t')
print()
lst=[['01','电风扇','美的',500],
['02','洗衣机','TCL',1000],
['03','微波炉','老板',400]]
print('编号\t\t名称\t\t\t品牌\t\t单价')
show(lst)
print('———————————格式化输出字符串—————————')
print('编号\t\t名称\t\t\t品牌\t\t单价')
for item in lst:
item[0]='0000'+item[0]
item[3]='¥{:.2f}'.format(item[3])
show(lst)
以及,我尝试用之前万能的输出表格的方法试了一下,需要注释几个地方,多调一下格式对齐,也能实现:

def show(lst):
for item in lst:
for i in item:
print(i, end='\t\t')
print()
def ShowTable():
table_titles = ['编号', '名称', '品牌', '单价']
max_wrap = 6
table_datas = [str('01\t\t电风扇\t美的\t\t500'), str('02\t\t洗衣机\tTCL\t\t1000'), str('03\t\t微波炉\t老板\t\t400')]
for i in range(len(table_datas) - 1):
if len(table_datas[i]) < max_wrap:
#table_datas[i] = table_datas[i] + ' ' * (max_wrap - len(table_datas[i])) # 剩余部分用空格补齐
table_titles[i] = table_titles[i] + ' ' * (max_wrap - len(table_titles[i]))
print('\t\t'.join(table_titles))
#print('\t'.join(table_datas))
for i in range(len(table_datas)):
print(table_datas[i])
lst=[['01','电风扇','美的',500],
['02','洗衣机','TCL',1000],
['03','微波炉','老板',400]]
print('编号\t\t名称\t\t\t品牌\t\t单价')
show(lst)
print('———————————格式化输出字符串—————————')
print('编号\t\t名称\t\t\t品牌\t\t单价')
for item in lst:
item[0]='0000'+item[0]
item[3]='¥{:.2f}'.format(item[3])+'\n'
show(lst)
print('-----------表格输出字符串-------------')
ShowTable()
本文介绍两个实用的Python编程案例:一是统计字符串中特定字符的出现次数;二是格式化输出商品列表,包括编号、名称、品牌及单价等信息,并通过字符串格式化确保输出整齐。
5610

被折叠的 条评论
为什么被折叠?



