Python 格式化输出详解
生活随笔
收集整理的這篇文章主要介紹了
Python 格式化输出详解
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
文章目錄
- 1 概述
- 2 用法
- 2.1 %
- 2.2 format (推薦)
1 概述
1. 格式化輸出(1) 按 '指定格式' 進(jìn)行輸出:如 '整數(shù)'、'字符串' 等2. 用法(1) % : 指定格式,如:%s 字符串(2) format: 自動匹配格式,如:f'{s}'2 用法
2.1 %
""" 整數(shù)類型 %d """ a = 1 b = 2print('a = %d, b = %d' % (a, b)) # a = 1, b = 2""" 浮點數(shù) %f """ f = 520.131415926 print('保留 3 位有效數(shù)字:%.3f' % f)""" 字符串 %s """ s = 'abc'print("字符串格式 : %s" % s) # abc print("右對齊,占位符 10 位 : %10s" % s) # abc print("左對齊,占位符 10 位 : %-10s" % s) # abc print("截取 2 位字符串 : %.2s" % s) # ab2.2 format (推薦)
簡寫:f"xxxx"
name = "張三" age = 18print(f"我叫 {name}, 今年 {age} 歲") # 我叫 張三, 今年 18 歲擴(kuò)展:
1. 位置匹配print("不帶編號: {} {}".format('hello', 'world')) # hello world print("帶編號: {0} {1}".format('hello', 'world')) # hello world print("帶編號,且調(diào)換順序: {0} {1} {0}".format('hello', 'world')) # hello world hello print("帶關(guān)鍵字: {a} {b}".format(a='hello', b='world')) # hello world2. 格式轉(zhuǎn)換print("二進(jìn)制數(shù):{:b}".format(2)) # 10 print("八進(jìn)制數(shù):{:o}".format(8)) # 10 print("十進(jìn)制數(shù):{:d}".format(10)) # 10 print("十六進(jìn)制數(shù):{:x}".format(16)) # 10print("冪運算:{:e},(用科學(xué)計數(shù)法打印數(shù)字)".format(10)) # 1.000000e+01 print("一般格式:{:g},(當(dāng)數(shù)值特別大的時候,用冪形式打印)".format(123)) # 123 print("數(shù)字:{:n},(當(dāng)值為整數(shù)時和'd'相同,值為浮點數(shù)時和'g'相同)".format(10.11)) # 10.11print("字符:{:c},(在打印之前將整數(shù)轉(zhuǎn)換成對應(yīng)的 Unicode 字符串)".format(2))print("百分?jǐn)?shù):{:%}".format(1)) # 100.000000%print("當(dāng)前時間(24 小時制):{:%Y-%m-%d %H:%M:%S}".format(datetime.datetime.now())) # 2020-09-23 23:26:003. 輸出內(nèi)容對齊:'{:<10}:左對齊', '{:>10}:右對齊', '{:^10}:居中對齊',占位符:10個字符print('左對齊:{:<10}|{:<10}|'.format('hello', 'world')) # "|" 僅為了觀察方便,可不寫 print('右對齊:{:>10}|{:>10}|'.format('hello', 'world')) print('居中對:{:^10}|{:^10}|'.format('hello', 'world'))左對齊:hello |world | 右對齊: hello| world| 居中對: hello | world |總結(jié)
以上是生活随笔為你收集整理的Python 格式化输出详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 企鹅的故事
- 下一篇: Python爬虫笔记【一】模拟用户访问之