溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python中format如何使用

發(fā)布時間:2020-09-23 09:36:01 來源:億速云 閱讀:161 作者:小新 欄目:編程語言

小編給大家分享一下python中format如何使用,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

python的format怎么用?

python的format函數(shù)用法

它增強了字符串格式化的功能?;菊Z法是通過 {} 和 : 來代替以前的 % 。format 函數(shù)可以接受不限個參數(shù),位置可以不按順序。

**例一:**format 函數(shù)可以接受不限個參數(shù),位置可以不按順序。

"{} {}".format("hello", "world")    # 不設(shè)置指定位置,按默認順序
運行結(jié)果:'hello world'
 "{0} {1}".format("hello", "world")  # 設(shè)置指定位置
運行結(jié)果:'hello world'
"{1} {0} {1}".format("hello", "world")  # 設(shè)置指定位置
運行結(jié)果:'world hello world'

例二:也可以設(shè)置參數(shù)。

print("網(wǎng)站名:{name}, 地址 {url}".format(name="Python教程", url="www.py.cn"))
# 通過字典設(shè)置參數(shù)
site = {"name": "Python教程", "url": "www.py.cn"}
print("網(wǎng)站名:{name}, 地址 {url}".format(**site))
# 通過列表索引設(shè)置參數(shù)
my_list = ['Python教程', 'www.py.cn']
print("網(wǎng)站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必須的
運行結(jié)果:
網(wǎng)站名:Python教程, 地址 www.py.cn
網(wǎng)站名:Python教程, 地址 www.py.cn
網(wǎng)站名:Python教程, 地址 www.py.cn

例三:也可以向 str.format() 傳入對象:

class AssignValue(object):
    def __init__(self, value):
        self.value = value
my_value = AssignValue(6)
print('value 為: {0.value}'.format(my_value))  # "0" 是可選的

輸出結(jié)果為:

value 為: 6

例四:下表展示了 str.format() 格式化數(shù)字的多種方法

print("{:.2f}".format(3.1415926));
3.14

數(shù)字格式化方法

數(shù)字 格式 輸出 描述

3.1415926 {:.2f} 3.14 保留小數(shù)點后兩位

3.1415926 {:+.2f} +3.14 帶符號保留小數(shù)點后兩位

-1 {:+.2f} -1.00 帶符號保留小數(shù)點后兩位

2.71828 {:.0f} 3 不帶小數(shù)

5 {:0>2d} 05 數(shù)字補零 (填充左邊, 寬度為2)

5 {:x<4d} 5xxx 數(shù)字補x (填充右邊, 寬度為4)

10 {:x<4d} 10xx 數(shù)字補x (填充右邊, 寬度為4)

1000000 {:,} 1,000,000 以逗號分隔的數(shù)字格式

0.25 {:.2%} 25.00% 百分比格式

1000000000 {:.2e} 1.00e+09 指數(shù)記法

13 {:10d} 13 右對齊 (默認, 寬度為10)

13 {:<10d} 13 左對齊 (寬度為10)

13 {:^10d} 13 中間對齊 (寬度為10)

‘{:b}’.format(11) 1011

‘{:d}’.format(11) 11

11的進制 ‘{:o}’.format(11) 13

‘{:x}’.format(11) b

‘{:#x}’.format(11) 0xb

‘{:#X}’.format(11) 0XB

^, <, > 分別是居中、左對齊、右對齊,后面帶寬度, : 號后面帶填充的字符,只能是一個字符,不指定則默認是用空格填充。

+ 表示在正數(shù)前顯示 +,負數(shù)前顯示 -; (空格)表示在正數(shù)前加空格

b、d、o、x 分別是二進制、十進制、八進制、十六進制。

例五:

給你一個字典:

t={‘year’:’2013’,’month’:’9’,’day’:’30’,’hour’:’16’,’minute’:’45’,’second’:’2’}

請按這樣的格式輸出:2013-09-30 16:45:02

def data_to_str(d):
    '''
    :param d: 日期字典
    :return: str 格式化后的日期
    '''
    s1='{} {:>02} {:>02}'.format(t['year'],t['month'],t['day'])
    s2='{} {:>02} {:>02}'.format(t['hour'],t['minute'],t['second'])
    print(s1,s2)
    print('-'.join(s1.split()),end=' ')
    print(':'.join(s2.split()))
    return 0
t={'year':'2013','month':'9','day':'30','hour':'16','minute':'45','second':'2'}
print(data_to_str(t))

運行結(jié)果:

2013 09 30 16 45 02
2013-09-30 16:45:02

以上是python中format如何使用的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI