python:格式化字符串,format

简介: python中format格式化字符串比 % 提供更加强大的输出特性1、位置参数format的元素输出流位置参数不受顺序约束,元素放置方式为{},只要format里有相对应的参数值即可,参数索引从0开始,传入...

python中format格式化字符串比 % 提供更加强大的输出特性

1、位置参数

format的元素输出流位置参数不受顺序约束,元素放置方式为{},只要format里有相对应的参数值即可,参数索引从0开始,传入位置参数列表时可用*进行读取

>>> myinfo = ['oldpan',22]
>>> print('my name is {}, age {}'.format('oldpan', 22))
my name is oldpan, age 22
>>> print('my name is {1}, age {0}'.format(22,'oldpan'))
my name is oldpan, age 22
>>> print('my name is {1}, age {0},and they often call me {1},'.format(22,'oldpan'))
my name is oldpan, age 22,and they often call me oldpan,
>>> print('my name is {}, age {}'.format(*myinfo))
my name is oldpan, age 22

2、使用关键字操作

只要关键字对的上,format也可以像字典一样进行操作

>>> myinfo = {'name':'oldpan','age':22}
>>> print('my name is {name}, age {age}'.format(name='oldpan', age=22))
my name is oldpan, age 22
>>> print('my name is {name}, age {age}'.format(**myinfo))
my name is oldpan, age 22

3、填充与格式化

使用格式为: [填充字符][对齐方式 <^>][宽度]

>>> '{0:*>10}'.format(10)    # 右对齐
'********10'
>>> '{0:*<10}'.format(10)    # 左对齐
'10********'
>>> '{0:*^10}'.format(10)    # 居中对齐
'****10****'

4、精度与进制

>>> '{0:.2f}'.format(1/3)
'0.33'
>>> '{0:b}'.format(10)     # 二进制
'1010'
>>> '{0:o}'.format(10)     # 八进制
'12'
>>> '{0:x}'.format(10)     # 16进制
'a'
>>> '{:,}'.format(12369132698)  # 千分位格式化
'12,369,132,698'

5、使用索引

>>> li
['hoho', 18]
>>> 'name is {0[0]} age is {0[1]}'.format(li)
'name is hoho age is 18
目录
相关文章
|
4天前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
154 99
|
7天前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
7天前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
7天前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
18天前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化
|
1月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
206 92
|
1月前
|
索引 Python
python 字符串的所有基础知识
python 字符串的所有基础知识
182 0
|
1月前
|
Python
Python字符串center()方法详解 - 实现字符串居中对齐的完整指南
Python的`center()`方法用于将字符串居中,并通过指定宽度和填充字符美化输出格式,常用于文本对齐、标题及表格设计。
|
2月前
|
PHP Python
Python format()函数高级字符串格式化详解
在 Python 中,字符串格式化是一个重要的主题,format() 函数作为一种灵活且强大的字符串格式化方法,被广泛应用。format() 函数不仅能实现基本的插入变量,还支持更多高级的格式化功能,包括数字格式、对齐、填充、日期时间格式、嵌套字段等。 今天我们将深入解析 format() 函数的高级用法,帮助你在实际编程中更高效地处理字符串格式化。
254 0

推荐镜像

更多