Python 格式化输出之f-string的使用
Background
字符串是各类编程语言中都很重要的一种变量类型,而且在实际开发中,字符串多与各类变量相互交互、共同作用,常见的有字符串拼接,格式化输出等手段,但是这两种手段都略显笨拙,于是,在Python3.6及更高版本中,Python引进了格式化输出的新手段–“f-string”,使得字符串与其他变量的交互融合变得更加便捷和优雅
f-string之前
在f-string新特性出现之前,字符串常用操作有:字符串拼接以及格式化输出:
字符串拼接
# python2
# 其他类型变量转换成字符串拼接
print "Welcome! The "+str(cnt)+"'s Student!"
# 直接拼接
print "Welcome! The", cnt , "\b's Student!"
# python3
# 其他类型变量转换成字符串拼接
print("Welcome! The "+str(cnt)+"'s Student!")
# 直接拼接
print("Welcome! The", cnt , "\b's Student!")
格式化输出
# python2
print "Welcome! The %d's Student!" % cnt
# python3
print("Welcome! The %d's Student!" % cnt)
f-string
一个{}就可以用来区分字串与变量引用,颇有几分前端渲染引擎语法的感觉,如:${user.name}
# Python3.6及以上
print(f"Welcome! The {cnt}'s Student!")