23

一文秒懂!Python字符串格式化之format方法详解

 3 years ago
source link: https://segmentfault.com/a/1190000037571463
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

format是字符串内嵌的一个方法,用于格式化字符串。以大括号 {} 来标明被替换的字符串,一定程度上与 % 目的一致。但在某些方面更加的方便

1、基本用法

1、按照{}的顺序依次匹配括号中的值

s = "{} is a {}".format('Tom', 'Boy')
print(s) # Tom is a Boy

s1 = "{} is a {}".format('Tom')
# 抛出异常, Replacement index 1 out of range for positional args tuple
print(s1)

2、通过索引的方式去匹配参数

这里需要注意的是,索引从0开始计算。

s = "{0} is a {1}".format('Tom', 'Boy')
print(s) # Tom is a Boy

s1 = "{1} is a {2}".format('Tom', 'Lily', 'Girl')
print(s1) # Lily is a Girl

字符串中索引的顺序可以打乱,并不影响匹配。

s = "{1} is a {0}".format('Boy', 'Tom', )
print(s) # Tom is a Boy

3、通过参数名来匹配参数

s = "{name} is a {sex}".format(name='Tom', sex='Boy')
print(s) # Tom is a Boy

同理,如果参数已经确定,可以直接利用{}进行格式化引用。

name = 'Tom'
sex = 'Girl'
# 以f开头表示在字符串中支持大括号内的python表达式
s = f"{name} is a {sex}"
print(s) # Tom is a Boy

4、混搭使用

可以通过索引,参数名来混搭进行匹配。

s = "My name is {}, i am {age} year old, She name is {}".format('Liming', 'Lily', age=10)
print(s) # My name is Liming, i am 10 year old, She name is Lily

需要注意的是,命名参数必须写道最后。负责会编译报错!

s = "My name is {}, i am {age} year old, She name is {}".format('Liming', age=10, 'Lily')
print(s)  # SyntaxError: positional argument follows keyword argument

另外,不可以索引和默认格式化混合使用。

s = "{} is a {0}".format('Boy', 'Tom', )
print(s)


s1 = "{} is a {1}".format('Boy', 'Tom', )
print(s1)

以上两种写法均报异常。

# ValueError: cannot switch from automatic field numbering to manual field specification

2、进阶用法

1、支持对参数部分引用

可以通过索引对参数的部分进行取值。如下:s[0] = w。

s = "The word is {s}, {s[0]} is initials".format(s='world')
# The word is world, w is initials
print(s)

2、数字的处理

普通的直接匹配数字没什么好说的,与基础部分的字符串匹配一样。

s = 'π is {}'.format(3.1415926)
print(s) # π is 3.1415926

如何使用format 保留两位小数呢? 需要使用 :.2f ,在用%进行格式化时我们使用的是 %:.2f

s = 'π is {:.2f}'.format(3.1415926)
print(s) # π is 3.14

s1 = 'π is %.2f'% 3.1415926
print(s1) # π is 3.14

同时这种方法还可以用于字符串截取,不过数字后面就不能加f了。

s = "{:.1}".format('Hello')
print(s) # H

给数字加千位符

s = "{:,}".format(1000000)
print(s) # 1,000,000

将数字转换成二进制

s = "{:b}".format(8)
print(s) # 1000

将数字转换成八进制

s = "{:o}".format(8)
print(s) # 10

将数字转换成十六进制

s = "{:X}".format(12)
print(s) # C

总结如下

  • b: 输出整数的二进制方式;
  • c: 输出整数对应的 Unicode 字符;
  • d: 输出整数的十进制方式;
  • o: 输出整数的八进制方式;
  • x: 输出整数的小写十六进制方式;
  • X: 输出整数的大写十六进制方式;

3、格式处理

通过 :+数字 指定转换后的字符串长度,不足的部分用空格补充

s = "{:2}b".format('a')
print(s) # a b  (a后面补了一个空格)
# 如果指定的长度小于参数的长度,按照原参数匹配
s1 = "{:2}World".format('Hello')
print(s1) # HelloWorld

4、字符的填充

可通过 :符号^数字 进行字符串的填充。 其中数字为填充后的字符串总长度。

s = "{:*^10}".format('Hello')
print(s) # **Hello***

s = "{:-^20}".format('123456')
print(s) # -------123456-------

如果数字小于字符串的长度,则不进行填充操作。

s = "{:*^3}".format('Hello')
print(s) # Hello

5、list、tuple的拆分

在format格式化时,可使用 * 或者 ** 进行对list、tuple拆分。

foods = ['fish', 'beef', 'fruit']
s = 'i like eat {} and {} and {}'.format(*foods)
# i like eat fish and beef and fruit
print(s)
foods = ['fish', 'beef', 'fruit']
s = 'i like eat {2} and {0} and {1}'.format(*foods)
# i like eat fruit and fish and beef
print(s)
dict_temp = {'name': 'Lily', 'age': 18} 
# 字典需要用 ** 进行拆分
s = 'My name is {name}, i am {age} years old'.format(**dict_temp)
print(s) # My name is Lily, i am 18 years old

史上最全Python资料汇总(长期更新)。隔壁小孩都馋哭了 --- 点击领取

nYn6VnE.png!mobile


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK