python 格式化输出字符串

全栈 shanhuhai 2744℃

格式化输出浮点数

print "The result is %6.2f" % 2.123

上面代码, 6 代表输出共占 6 个字符,2 表示小数部分取两位,这与 C 语言 printf 中的格式化规则是一致的

补 0 :

print "The result is %06.2f" % 10/3.0

在 python 中格式化输出串与 C 语言一致

python 还可以用 tuple (元组) 和 dict (字典) 来格式化输出
使用 tuple 来格式化输出:

print "The site's domain is %s,it is a %s" % ("dahouduan.com", "blog")

使用 dict 来格式化输出:

print "Welcome %(name)s login  %(site)s  " % {"name":"shanhuhai","site":"dahouduan.com"}

转载请注明:大后端 » python 格式化输出字符串

付费咨询
喜欢 (1)or分享 (0)