日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

Python 格式化输出详解

發(fā)布時間:2023/12/18 python 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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) # ab

2.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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。