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='tt')
print()
lst=[['01','电风扇','美的',500],
['02','洗衣机','TCL',1000],
['03','微波炉','老板',400]]
print('编号tt名称ttt品牌tt单价')
show(lst)
print('———————————格式化输出字符串—————————')
print('编号tt名称ttt品牌tt单价')
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='tt')
print()
def ShowTable():
table_titles = ['编号', '名称', '品牌', '单价']
max_wrap = 6
table_datas = [str('01tt电风扇t美的tt500'), str('02tt洗衣机tTCLtt1000'), str('03tt微波炉t老板tt400')]
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('tt'.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('编号tt名称ttt品牌tt单价')
show(lst)
print('———————————格式化输出字符串—————————')
print('编号tt名称ttt品牌tt单价')
for item in lst:
item[0]='0000'+item[0]
item[3]='¥{:.2f}'.format(item[3])+'n'
show(lst)
print('-----------表格输出字符串-------------')
ShowTable()



