字符串格式化代碼:
格式 | 描述 |
---|---|
%% | 百分號標記 |
%c | 字符及其ASCII碼 |
%s | 字符串 |
%d | 有符號整數(十進制) |
%u | 無符號整數(十進制) |
%o | 無符號整數(八進制) |
%x | 無符號整數(十六進制)a-f |
%X | 無符號整數(十六進制大寫字符)A-F |
%e | 浮點數字(科學計數法) |
%E | 浮點數字(科學計數法,用E代替e) |
%f | 浮點數字(用小數點符號)默認精度為6位 |
%g | 浮點數字(根據值的大小采用%e或%f) |
%G | 浮點數字(類似於%g) |
%p | 指針(用十六進制打印值的內存地址) |
%n | 存儲輸出字符的數量放進參數 |
整數不包含精度問題
1.打印字符串 %s
print("My name is %s" %("Alfred.Xue")) #輸出效果:
My name is Alfred.Xue
2.打印整數 %d
print("I am %d years old." %(25)) #輸出效果:
I am 25 years old.
3.打印浮點數 %f
print ("His height is %f m"%(1.70))
#輸出效果:
His height is 1.700000 m
4.打印浮點數(指定保留兩位小數) %.2f
print ("His height is %.2f m"%(1.70))
#輸出效果: His height is 1.70 m
5.指定占位符寬度 %8d %8.2f 多個占位符用括號
print ("Name:%10s Age:%8d Height:%8.2f"%("Alfred",25,1.70))
#輸出效果: Name: Alfred Age: 25 Height: 1.70
6.指定占位符寬度(左對齊)默認右邊對齊,負號代碼左邊對齊 %-10s %-8d %-8.2f
print ("Name:%-10s Age:%-8d Height:%-8.2f"%("Alfred",25,1.70))
#輸出效果:
Name:Alfred Age:25 Height:1.70
7.指定占位符(只能用0當占位符?) %08d %08.2f
print ("Name:%-10s Age:%08d Height:%08.2f"%("Alfred",25,1.70))
#輸出效果: Name:Alfred Age:00000025 Height:00001.70
8.科學計數法
format(0.0026,'.2e')
#輸出效果: '2.60e-03'
練習字符串
1 #!usr/bin/python3 2 3 inputstr = input("請輸入字符串") 4 ##!!!!str作為字符串名不建議使用,容易混淆str()函數 5 6 print("字符中存在%s個a" % inputstr.count('a')) 7 print("字符中存在%s個空格" % inputstr.count(' ')) 8 print("字符中第一個字符編碼%s\n\n" % ord(inputstr[0])) 9 10 11 inputNum = input("請輸入整數") 12 while not (inputNum.isdigit() and (int(inputNum)>=0 and int(inputNum)<=256)): 13 if not inputNum.isdigit(): 14 inputNum = input("輸入的不是數字,請重新輸入") 15 continue 16 if not (int(inputNum)>=0 and int(inputNum)<=256): 17 inputNum = input("輸入的數字值太大,請重新輸入") 18 19 print("%s對應的ascii的字符為%s" % (inputNum, chr(int(inputNum)))) 20 21 """ 22 if len(inputstr)==0: 23 print("沒有輸入數據!!!!") 24 quit() 25 26 if inputstr[::] == inputstr[::-1]: 27 print("是回文") 28 else: 29 print("不是回文") 30 """ 31 32 33 34 """ 35 print("第一個字符:" + inputstr[0]) 36 37 #print(inputstr[int(len(inputstr)/2)]) 38 #print(len(inputstr)%2) 39 40 if len(inputstr)%2 != 0: 41 print("中間第"+str(len(inputstr)//2+1)+"個字符為:"+inputstr[len(inputstr)//2]) 42 ##!!!!注意len()/2得到的值為float型 43 else: 44 print("沒有中間字符") 45 46 print("最后一個字符:"+inputstr[-1]) 47 """