欢迎访问mehome的博客

omorrow is another day.T
Fork me on GitHub

Python——format汇总

一、str.format

按照指定格式格式化字符串,然后返回格式化的字符串,源字符串不变。

以下是Python2.7环境。

1.1、按照位置替换

参考下面例子:

1
2
3
4
5
6
7
8
9
10
11
>>> s = '{0} is {1}'
>>> s.format('wo','haoren')
'wo is haoren'
>>> s
'{0} is {1}'
>>> s = '{} {} age.'
>>> s.format('wo',29)
'wo 29 age.'
>>> s = '{0} is {1},{0} {2} age.'
>>> s.format('wo','haoren',20)
'wo is haoren,wo 20 age.'

注意:如果源字符串中有{}这个大括号。那么这个字符串中的{}需要用重复的两遍才可以。否则会报错。

1
2
3
4
5
>>> s = 'zheshi {} kuo hao{{}}'
>>> s.format('da')
'zheshi da kuo hao{}'
>>> s
'zheshi {} kuo hao{{}}'
1
2
3
4
5
>>> s = 'zheshi {} kuo hao{}'
<strong>>>> s.format('da')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range</strong>

 

1.2、按照名字匹配替换

参考下面例子:

这个按照名字匹配可以理解为按照字典key值匹配对应的value替换到源字符串对应的key的位置。1.1中的key是位置,这里面把这个数字改为字符串索引即可。

1
2
3
>>> s = '{name} {age} age.{name} is {0}'
>>> s.format('student',name='wo',age=20)
'wo 20 age.wo is student'

 

1.3、按照索引替换

参考下面例子:

按照索引可以分为按照列表索引和按照字典的key取值两种。

  • 按照列表
1
2
3
4
>>> s = '{0[0]} {0[1]} age.{0[0]} is {0[2]}'
>>> a = ['wo',20,'student']
>>> s.format(a)
'wo 20 age.wo is student'
  • 按照字典key值
1
2
3
4
>>> d = {'name':'wo','age':20,'job':'student'}
>>> s = '{0[name]} {0[age]} age.{0[name]} is {0[job]}'
>>> s.format(d)
'wo 20 age.wo is student'

 

1.4、按照对象格式化

参考下面例子:

1
2
3
4
>>> import sys
>>> import math
>>> "math.pi=={0.pi}sys.maxunicode=={1.maxunicode}".format(math,sys)
'math.pi==3.14159265359sys.maxunicode==65535'

 

1.5、格式规约——字符串格式规约

格式限定符是通过{}中带:号带入的。后面跟随的可选字符对是:

填充字符X对齐字符(<左对齐,^中间对齐,>右对齐)X可选最小宽度(如果指定最大宽度,就用句号隔开并再写一个整数)

参考下面例子:

1
2
3
>>> s = '{0:-^8} shi haoren'
>>> s.format('wo')
'---wo--- shi haoren'
1
2
3
4
5
6
7
8
9
>>> s = '{0:.{1}} shi haoren'
>>> s.format('wo',1)
'w shi haoren'
>>> s.format('wo',2)
'wo shi haoren'
>>> s.format('wo',0)
' shi haoren'
>>> s.format('wo',11)
'wo shi haoren'

1.6、格式规约——整数格式规约

格式限定符是通过{}中带:号带入的。后面跟随的可选字符对是:
填充字符X对齐字符(<左对齐,^中间对齐,>右对齐,=用于在符号和数字之间进行填充)X"+"表示必须输出符号,"-"表示只输出负数符号," "表示正数输出空格,负数输出符号X可选#引导b(二进制)、o(八进制)、x(16进制)可选最小宽度(不能指定最大宽度)

参考下面例子:

1
2
3
4
5
6
7
8
9
10
把十进制数字转换为二进制数,不足8位在前面用0补齐8位:
>>> "{0:08b}".format(2)
'00000010'
>>> "{0:08b}".format(10)
'00001010'
二进制、八进制、十六进制:
>>> "{0:b},{0:o},{0:x},{0:X}".format(10)
'1010,12,a,A'
>>> "{0:#b},{0:#o},{0:#x},{0:#X}".format(10)
'0b1010,0o12,0xa,0XA'
1
2
3
4
5
>>> "{0:0=8b}".format(10)
'00001010'
10进制数转换为8位二进制数,如果不足8位在后面用0补全:
>>> "{0:0<8b}".format(10)
'10100000'

 

二、

posted @   mehome  阅读(1661)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示