第十五課 練習(xí)題
'''
1. 編寫一個Python程序,從控制臺輸入一個字符串(保存到變量s中),
然后通過while循環(huán)不斷輸入字符串(保存到變量subStr中),
并統(tǒng)計subStr在s中出現(xiàn)的次數(shù),最后利用format方法格式化統(tǒng)計結(jié)果。
'''
s = input("請輸入一個字符串:")
while True:
subStr = input("請輸入要統(tǒng)計的字符串:")
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("'{}'在'{}'中出現(xiàn)了{}次".format(subStr, s, count))
輸出的結(jié)果為:
請輸入一個字符串:l love python
請輸入要統(tǒng)計的字符串:o
'o'在'l love python'中出現(xiàn)了2次
-------------------------------
'''
2. 從控制臺輸入n,利用format方法生成一個星號三角形
*
***
*****
*******
'''
floorStr = input('請輸入一個層數(shù):')
floor = int(floorStr)
num = floor * 2 -3 # 17
while floor > 0:
print("{:<{a}}{:*<}".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(" ",""))
'''
請輸入一個層數(shù):10
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
分享題目:33pythonformat練習(xí)題利用format方法
網(wǎng)頁路徑:
http://weahome.cn/article/gdgecj.html