第十五课 练习题
'''
1. 编写一个Python程序,从控制台输入一个字符串(保存到变量s中),
然后通过while循环不断输入字符串(保存到变量subStr中),
并统计subStr在s中出现的次数,最后利用format方法格式化统计结果。
'''
s = input("请输入一个字符串:")
while True:
subStr = input("请输入要统计的字符串:")
if subStr == ":exit":
break;
i = 0
count = 0
while i < len(s):
index = s.find(subStr, i)
if index > -1:
count += 1
i = index + len(subStr)
else:
break;
print("'{}'在'{}'中出现了{}次".format(subStr, s, count))
输出的结果为:
请输入一个字符串:l love python
请输入要统计的字符串:o
'o'在'l love python'中出现了2次
-------------------------------
'''
2. 从控制台输入n,利用format方法生成一个星号三角形
*
***
*****
*******
'''
floorStr = input('请输入一个层数:')
floor = int(floorStr)
num = floor * 2 -3 # 17
while floor > 0:
print("{:<{a}}{:*<{b}}".format(" ","",a =floor,b=(num - (floor - 2)*2)))
floor -= 1
'''
print("{:<10}{:*<1}".format(" ",""))
print("{:<9}{:*<3}".format(" ",""))
print("{:<8}{:*<5}".format(" ",""))
print("{:<7}{:*<7}".format(" ",""))
print("{:<6}{:*<9}".format(" ",""))
print("{:<5}{:*<11}".format(" ",""))
print("{:<4}{:*<13}".format(" ",""))
print("{:<3}{:*<15}".format(" ",""))
print("{:<2}{:*<17}".format(" ",""))
print("{:<1}{:*<19}".format(" ",""))
'''
请输入一个层数:10
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/185017.html