通过转换定义符的方式可进行格式化输出,如下所示%s
就是转换定义符,它叫啥不重要,重要的是要知道它会被%
后面的变量name的值所自动替换。
>>> name = "Jerk" >>> print "His name is %s. His age is 508." % name His name is Jerk. His age is 508.
%s
只能用来替换字符串,不同类型的转义定义符只能用来替换相应类型的对象。常用的转义定义符如下所示:
转义定义符 | 说明 |
---|---|
%s |
用来替换字符串 |
%d |
用来替换整型 |
%f |
用来替换浮点型 |
示例如下:
name = "Jerk" print "I am %s ^_^" % name age = 508 print "I'm %d years old." % age eq = -250.250 print "My EQ score is %f -_-" % eq
同一个字符串中,有多个转义定义符,可按照对应顺序如下操作:
>>> name = "Jerk" >>> age = 508 >>> eq = -250.250 >>> print "I am %s. I'm %d years old. My EQ is %f." % (name, age, eq) I am Jerk. I'm 508 years old. My EQ is -250.250000.
上述示例中,浮点型对象的格式化输出中,若想保留小数至指定位数,可查看这里。
format方式格式化输出的功能非常强大,先说说最基础的运用方式:
>>> print "PI is {}.".format( 3.1415926 ) PI is 3.1415926. >>> print "My name is {}, and my age is {}.".format( "Jerk", 508 ) My name is Jerk, and my age is 508.
带有关键词的format方式最为经典:
name="Jerk" age = 508 print "I'm {name}, and {age} old.".format( name=name, age=age )