使用 {}.format 对字符串进行格式(一)

语法格式:

{ [field_name] ["!" conversion] [":" format_spec] }.format()

各选项的详细解释:

field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
	arg_name          ::=  [identifier | digit+]
	attribute_name    ::=  identifier
	element_index     ::=  digit+ | index_string
		index_string      ::=  <any source character except "]"> +
		
conversion        ::=  "r" | "s" | "a"

format_spec     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
	fill            ::=  <any character>
	align           ::=  "<" | ">" | "=" | "^"
	sign            ::=  "+" | "-" | " "
	width           ::=  digit+
	grouping_option ::=  "_" | ","
	precision       ::=  digit+
	type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

具体案例:

1、使用参数的索引号作为 field_name

'{0}'.format("ab", 1, "cd")  # 输出:'ab'。对第一个参数进行格式化

# 如果 field_name 为空(即不写参数的索引号),则依次代表0,1,2...
"From {} to {}".format("A", "B", "c", 1)  # 输出:'From A to B'。等价于 "From {0} to {1}".format("A", "B", "c", 1)

2、使用参数的名字作为 field_name

"My quest is {A}".format(B='what', A='that')  # 输出:'My quest is that'   

"""
注意:当 format 的参数以元组形式呈现的时候,只能用参数的索引作为 field_name;
	当 format 的参数以字典形式呈现的时候,只能用参数的名字作为 field_name。
以下两种写法均会报错
"""
# "My quest is {1}".format(B='what', A='that')  # 将会报错:IndexError: Replacement index 1 out of range for positional args tuple
# "My quest is {what}".format('what', 'that')  # 将会报错:KeyError: 'what'

"""但是,如果参数是 元组+字典形式"""
"My quest is {}".format('what', A='that')  # 输出:'My quest is what'
"My quest is {A}".format('what', A='that')  # 输出:'My quest is that'

3、使用参数的属性作为 field_name

class Test:
    def __init__(self):
        self.name = "老王"
        self.age = 47
        
test = Test()     
"This test's name={0.name} , age={0.age}".format(test)  # 输出:"This test's name=老王 , age=47"

"""但是,下面这种写法会报错"""
# "This test's name={test.name} , age={test.age}".format(test)  # 报错:KeyError: 'test'
# 应该写为:
"This test's name={test.name} , age={test.age}".format(test=test)  # 输出:"This test's name=老王 , age=47"

4、使用参数的切片作为 field_name

"我是隔壁 老{names[2]}".format(names=("李", "刘", "王", "吴"))  # 输出:'我是隔壁 老王'

5、三种转换标志:!s(将调用str())、!r(将调用repr())、!a(将调用ascii())

type('{string!s}'.format(string=2))  # 输出:str;而 type(2) = int

'this is a {string!r}'.format(string='strings')  # 输出:"this is a 'strings'"

"这是一个{!a}".format("测试")  # 输出:"这是一个'\\u6d4b\\u8bd5'"

更多链接:

1、选项 format_spec 的使用
2、str()、repr() 与 ascii() 的区别

你可能感兴趣的:(python,字符串)