第一种格式化输出:
%s,表示格化式一个对象为字符
%d,整数
“Hello, %s”%“zhang3” => “Hello, zhang3”
“%d”%33 => “33”
“%s:%d”%(“ab”,3) => “ab:3”
%字符:标记转换说明符的开始。
%s,表示格化式一个对象为字符
%d,整数
“Hello, %s”%“zhang3” => “Hello, zhang3”
“%d”%33 => “33”
“%s:%d”%(“ab”,3) => “ab:3”
%字符:标记转换说明符的开始。
在%的左侧放置一个字符串(格式化字符串),而右侧则放置希望格式化的值。
第二种格式化输出:
Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
基本语法是通过 {} 和 : 来代替以前的 % 。
format 函数可以接受不限个参数,位置可以不按顺序。
例如:
“{} {}”.format(“hello”, “world”) # 不设置指定位置,按默认顺序
‘hello world’
“{0} {1}”.format(“hello”, “world”) # 设置指定位置
‘hello world’
“{1} {0} {1}”.format(“hello”, “world”) # 设置指定位置
‘world hello world’