33 python format练习题 利用format方法生成一个星号三角形
第十五课 练习题
‘‘‘
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
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16