python基礎(六)
阿新 • • 發佈:2018-12-19
格式化輸出有兩種%和format函式
format的功能要比百分號方式強大。%用法的格式
1 s1 = "i am %s,%d years old" % ('jeck',26) #按位置順序依次輸出 2 s2 = "i am %(name)s, i am %(age)d years old" % {'name':'jeck','age':26} #自定義key輸出 3 s3 = "i am %(name)+10s, i am %(age)d years old, i am %(height).2f" % {'name':'jeck','age':26,'height':1.7512} #定義名字寬度為10,並右對齊.定義身高為浮點型別,保留小數點2位 4 s4 = "原數: %d, 八進位制:%o , 十六進位制:%x" % (15,15,15) #八進位制\十六進位制轉換 5 s5 = "原數:%d, 科學計數法e:%e, 科學計數法E:%E" %(1000000000,1000000000,1000000000) #科學計數法表示 6 s6 = "百分比顯示:%.2f %%" % 0.75 #百分號表示
format 函式可以接受不限個引數,位置可以不按順序。
>>>"{} {}".format("hello", "world") #不設定指定位置,按預設順序 'hello world' >>> "{0} {1}".format("hello", "world") # 設定指定位置 'hello world' >>> "{1} {0} {1}".format("hello", "world") # 設定指定位置 'world hello world'
print("{name},{sex}".format(name="zhangsan", sex="男")) # 通過字典設定引數 site = {"name": "zhangsan", "sex": "男"} print("姓名:{name}, 性別 {sex}".format(**site)) # 通過列表索引設定引數 my_list = ['zhangsan', '男'] print("姓名:{0[0]}, 性別 {0[1]}".format(my_list)) # "0" 是必須的
對數值型別的格式化
接收控制檯輸入用input函式(需要注意的是input函式接收返回的是字串形式的資料)