美文网首页
格式化输出

格式化输出

作者: 夜醉梦紅尘 | 来源:发表于2019-10-04 15:39 被阅读0次

https://www.jianshu.com/p/cd29ac885fbf
一、简单介绍
字符串的格式化输出目前有两种方式

% 方式(陈旧)
str.format() 方式(新式,官方推荐)
f-string 方式 (Python3.6 及以上推荐使用)

三种方法:% , f"{arg}" , "{}".format(arg)

tpl = "i am {}, age {}, {}"
r = tpl.format("yangge", 18, 'yangge')

tpl = "i am {0}, age {1}, really {0}"
print(tpl.format("xiguatian", 18))

tpl = "i am {name}, age {age}, really {name}"
print(tpl.format(name="xiguatian", age=18))

tpl = "i am {0[0]}, age {0[1]}, really {1[2]}"
print(tpl.format([1, 2, 3], [11, 22, 33]))

tpl = "i am {:s}, age {:d}, money {:f}"
print(tpl.format("seven", 18, 88888.1))

tpl = "i am {name:s}, age {age:d}"
tpl.format(name="xiguatian", age=18)

tpl = "i am {name:s}, age {age:d}"
tpl.format(**{"name": "xiguatian", "age": 18})

tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X},\
      {0:.2%}"
print(tpl.format(15))

f"{}" 方法

f "{2 * 37}" 

f"{to_lowercase(name)} is strong."     #中可以写个函数

f"{self.first_name} {self.last_name} is {self.age}."    #使用类对象

f"Hi {name}. "
    f"You are a {profession}. "
    f"You were in {msg}."      
与
f"Hi {name}. "
    "You are a {profession}. "
    "You were in {msg}."
等价

相关文章

网友评论

      本文标题:格式化输出

      本文链接:https://www.haomeiwen.com/subject/ebhcyctx.html