字符串格式化方法调用——格式化方法基础

未匹配的标注

字符串对象的format方法,在Python2.6,2.7和3.X中可用,是基于普通函数调用语法,而非表达式。具体地说,它使用被作用字符串作为模板,接收代表任何数量的参数,这些参数代表根据模板替换的值。

它的使用要求了解函数和调用,但大多数都简单易懂。在被作用字符串中,花括号指定替换目标和参数,这些目标和参数将通过位置(比如:{1})或关键字(如:{food}),或从2.7,3.1版本开始的相对位置({})来插入。在第18章深入学习参数传递时将学到:函数和方法的参数可以通过位置或关键字名字传递,Python收集任意多的位置和关键字参数的能力允许这些通用的方法调用模式。比如:

>>> template = '{0}, {1} and {2}' # 通过位置
>>> template.format('spam', 'ham', 'eggs')
'spam, ham and eggs'
>>> template = '{motto}, {pork} and {food}' # 通过关键字
>>> template.format(motto='spam', pork='ham', food='eggs')
'spam, ham and eggs'
>>> template = '{motto}, {0} and {food}' # 通过两种方法
>>> template.format('ham', motto='spam', food='eggs')
'spam, ham and eggs'
>>> template = '{}, {} and {}' # 通过相对位置
>>> template.format('spam', 'ham', 'eggs') # 在 3.1 和 2.7 中新增
'spam, ham and eggs'

通过比较,上一节的格式化表达式可以更简洁一些,但使用字典而非关键字参数,且不允许为值源提供那么大的灵活性(这可能是优点或缺点,取决于观察角度);更多关于这两个技术如何比较请见下面:

>>> template = '%s, %s and %s' # 通过表达式是一样的
>>> template % ('spam', 'ham', 'eggs')
'spam, ham and eggs'
>>> template = '%(motto)s, %(pork)s and %(food)s'
>>> template % dict(motto='spam', pork='ham', food='eggs')
'spam, ham and eggs'

注意这里使用 dict()(在第4章中引入,在第8章中全面讲述)来从关键字参数创建字典;它常是 {...}字面量的一种更整洁的可选方法。当然,在格式化方法调用中的被作用字符串也可以是一个字面量(它创建了一个临时的字符串),且任意的对象类型都能在目标处被代替,很像表达式的 %s码:

>>> '{motto}, {0} and {food}'.format(42, motto=3.14, food=[1, 2])
'3.14, 42 and [1, 2]'

%表达式和其它的字符串方法一样,format创建并返回了新的字符串对象,它可以被立即打印或保存以备后用(回忆一下:字符串是不可变的,所以format真的必须创建一个新对象)。字符串格式化不只是为了显示:

>>> X = '{motto}, {0} and {food}'.format(42, motto=3.14, food=[1, 2])
>>> X
'3.14, 42 and [1, 2]'
>>> X.split(' and ')
['3.14, 42', '[1, 2]']
>>> Y = X.replace('and', 'but under no circumstances')
>>> Y
'3.14, 42 but under no circumstances [1, 2]'

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~