python之字符串格式化方法str.format()详解

字符串格式化方法str.format()功能十分强大,在平时应用也比较多,今天我们来了解一下str.format()方法

>>> help(str.format)
Help on method_descriptor:

format(...)
    S.format(*args, **kwargs) -> str

    Return a formatted version of S, using substitutions from args and kwargs.
    The substitutions are identified by braces ('{' and '}').

帮助文档显示的内容非常简单。下面介绍具体应用常见的几种格式化方式:

'Hello {}'.format('Word')===>Hello Word
-------------------------------------------------
'你喜欢{2}吗?难道你喜欢{1},我猜你喜欢{0}'.format('java','c++','python')
===>你喜欢python吗?难道你喜欢c++,我猜你喜欢java
---------------------------------------------------
name='james'
age=12
'我的名字是{},年龄是{}'.format(name,age)
===>我的名字是james,年龄是12
-----------------------------------------------------
'我的名字是{name},年龄{age}'.format(name='bob',age='30')
===>>我的名字是bob,年龄30
----------------------------------------------------
coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
'Coordinates: {latitude}, {longitude}'.format(**coord)
===>Coordinates: 37.24N, -115.81W
-----------------------------------------------------
'{}-{}-{}'.format(*'abc')==>>a-b-c
-------------------------------------------------
'{:*>10}'.format('love you')
#右对齐默认用空格填充,这个例子设置星号填充
===>>**love you
-------------------------------------------------------
'{:*^30}'.format('centered') 
#居中对齐,默认空格填充,这个例子用性星号填充
===>>>***********centered***********
------------------------------------------------------
'{:*<10}'.format('love you')
#左对齐默认用空格填充,这个例子设置星号填充
=====>>>>love you**
-------------------------------------------------------
'{:.4f}; {:.3f};{:f}'.format(3.14, -3.14,3)
#浮点数保留指定位数小数,未指定则默认六位
===>>>3.1400; -3.140;3.000000
--------------------------------------------------------
"int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
#十进制,16进制,八进制,2进制转换
===>>>int: 42; hex: 2a; oct: 52; bin: 101010 
-------------------------------------------------------
"int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
#加上#好之后
====>>>int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010
--------------------------------------------------------
'{:,}'.format(1234567890)#用逗号作为千位分割符
===》》》1,234,567,890
------------------------------------------------
points=19
total=22
'{:.2%}'.format(19/22)#表示百分数==>>86.36%
-----------------------------------------------------
import datetime
d = datetime.datetime(2010, 7, 4, 12, 15, 58)
st='{:%Y-%m-%d %H:%M:%S}'.format(d)
#格式化时间
==>>>2010-07-04 12:15:58
----------------------------------------------------
octets = [192, 168, 0, 1]
'{:02X}{:02X}{:02X}{:02X}'.format(*octets)
===>>>C0A80001

以上就是各种格式化字符串的方法,部分例子引用于python官方文档。
如果您觉得有用,求赞!!!
欢迎留言互相交流!!!
在这里插入图片描述

发布了23 篇原创文章 · 获赞 5 · 访问量 377

猜你喜欢

转载自blog.csdn.net/weixin_43287121/article/details/105102237