Skip to content

26.22 Python格式化字符串

https://scz.617.cn/python/201911141329.txt

A:


传统方案

name = "nonexist" age = 83 email = "[email protected]" out = """ name : %s age : %d email : %s """ % ( name, age, email ) print( out )


name = "nonexist" age = 83 email = "[email protected]" out = ''' name : {name} age : {age} email : {email} '''.format( name=name, age=age, email=email ) print( out )


name = "nonexist" age = 83 email = "[email protected]" out = ''' name : {0} age : {1} email : {2} '''.format( name, age, email ) print( out )


后面的方案只适用于Python3

name = "nonexist" age = 83 email = "[email protected]" out = f''' name : {name} age : {age} email : {email} ''' print( out )


name = "nonexist" age = 83 email = "[email protected]" out = ''' name : {name} age : {age} email : {email} '''.format_map( vars() ) print( out )


class sth : def init ( self, name, age, email ) : self.name = name self.age = age self.email = email

x = sth( "nonexist", 83, "[email protected]" ) out = ''' name : {name} age : {age} email : {email} '''.format_map( vars( x ) ) print( out )


A: bluerust 2024-11-15

Python f format 有个很有意思的用法

a, b = 0x1000, 0x222 print(f"{a + b = :#x}") a + b = 0x1222

即 curly braces 里的内容会被保留