目錄
str.format()用法說明
格式化字符串的函數 str.format(),它增強了字符串格式化的功能。
基本語法是通過{} 和 :
來代替以前的 % 。【真的巨巨巨方便】
代碼示例
str.format()可以接受不限個參數,位置可以不按順序。
print("{} {}".format("hello", "world")) #不設置指定位置,按默認順序
print("{0} {1}".format("hello", "world")) #設置指定位置
print( "{1} {0} {1}".format("hello", "world")) # 設置指定位置
str.format()可以設置參數、通過字典設置參數、通過列表索引設置參數
print('{0},{1}'.format('xpt', 18))
print('{},{},{}'.format('xpt', 'fm', 18))
#可以設置參數
print('{name},{sex},{age}'.format(age=18, sex='fm', name='xpt'))
# 通過字典設置參數
site = {'name': 'xpt', 'url': 'https://xxpt.github.io/xxpt.github.io/'} # 字典dict格式 {'key':vale}
print("Author:{name}, Blog: {url}".format(**site))
# 通過列表索引設置參數
my_list = ['xpt', 'https://xxpt.github.io/xxpt.github.io/']
print("Author:{0[0]}, Blog: {0[1]}".format(my_list)) # "0" 是必須的
my_list2 = ['baidu','https://www.baidu.com/']
print("sitename:{1[0]}, url: {1[1]}".format(my_list,my_list2))
可以向 str.format() 傳入對象
class authorage(object):
def __init__(self, value):
self.value = value
author_age = authorage(18)
print('Author age: {0.value}'.format(author_age))
# 0可以去掉,0表示format函數裏第一個對象,.value取屬性值
str.format() 格式化數字的方法
1、精度格式化
描述 | 格式 |
---|---|
保留小數點後兩位 | {:.2f} |
顯示符號,並保留小數點後三位(+ 表示在正數前顯示 +,負數前顯示 -) | {:+.3f} |
不帶小數 | {:.0f} |
print("{:.2f}".format(3.1415926))#保留小數點後兩位
print("{:+.3f}".format(3.1415926))#帶符號保留小數點後兩位
print("{:.0f}".format(-3.1415926))#不帶小數
2、b、d、o、x分別是二進制、十進制、八進制、十六進制
print('{:b}'.format(11))
print('{:d}'.format(11))
print('{:o}'.format(11))
print('{:x}'.format(11))
3、以逗號分隔的數字、百分比格式、指數記法
描述 | 格式 |
---|---|
以逗號分隔的數字 | {:,} |
百分比格式 | {:.2%} |
指數記法 | {:.2e} |
print("{:,}".format(100000))#以逗號分隔的數字
print("{:.2%}".format(0.23456))#百分比格式
print("{:.2e}".format(0.23456))#指數記法
填充與對齊
關於對齊:
^、<、>分別是居中、左對齊、右對齊,後面帶寬度數字
:號後面帶填充的字符,只能是一個字符,不指定的話默認是用空格填充
描述 | 格式 |
---|---|
右對齊 (寬度爲10) | {:>10d} |
左對齊 (寬度爲10) | {:<10d} |
中間對齊 (寬度爲10) | {:^10d} |
關於填充:
寬度指的是填充完的總寬度
描述 | 格式 |
---|---|
數字補零 (填充左邊, 寬度爲2) | {:0>2d} |
數字補x (填充右邊, 寬度爲4) | {:x<4d} |
可以使用大括號 {} 來轉義大括號
print ("{} 對應的位置是 {{12}}".format("abc"))