Python:print()语句中的%运算符

时间:2013-12-08 06:20:34

标签: python syntax

我刚刚看到这个Python代码,我的问题是关于print语句中的语法:

class Point(object):
    """blub"""
    #class variables and methods

blank = Point
blank.x = 3.0
blank.y = 4.0    
print('(%g,%g)' % (blank.x,blank.y))

此print语句只打印(3.0,4.0),即blank.x和blank.y中的值。

我不理解最后一行(blank.x,blank.y)前面的运算符。它做了什么以及在哪里可以在文档中找到它?

谷歌搜索,我总是以模数运算符结束。

3 个答案:

答案 0 :(得分:7)

'(%g,%g)'是模板,(blank.x,blank.y)是需要填充的值,而不是%g%g%运营商就是这样做的。它被称为String interpolation or formatting operator

答案 1 :(得分:7)

简介

python中的%运算符用于字符串替换。 String和Unicode对象有一个独特的内置操作:%operator(modulo)。

这也称为字符串格式化或插值运算符。

给定格式%值(其中format是字符串或Unicode对象),格式中的%转换规范将替换为零个或多个值元素。效果类似于在C语言中使用sprintf()。

如果format是Unicode对象,或者使用%s转换转换的任何对象是Unicode对象,则结果也将是Unicode对象。


用法

'd' Signed integer decimal.  
'i' Signed integer decimal.  
'o' Signed octal value. (1)
'u' Obsolete type – it is identical to 'd'. (7)
'x' Signed hexadecimal (lowercase). (2)
'X' Signed hexadecimal (uppercase). (2)
'e' Floating point exponential format (lowercase).  (3)
'E' Floating point exponential format (uppercase).  (3)
'f' Floating point decimal format.  (3)
'F' Floating point decimal format.  (3)
'g' Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.  (4)
'G' Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.  (4)
'c' Single character (accepts integer or single character string).   
'r' String (converts any Python object using repr()).   (5)
's' String (converts any Python object using str()).    (6)
'%' No argument is converted, results in a '%' character in the result.

这些是可以替代的值。要替换,您只需遵循以下语法:

string%values #where string is a str or unicode and values is a dict or a single value

实施例

>>> print '%(language)s has %(number)03d quote types.' % \
...       {"language": "Python", "number": 2}
Python has 002 quote types.

>>> print "My name is %s"%'Anshuman'
My name is Anshuman

>>> print 'I am %d years old'%14
I am 14 years old

>>> print 'I am %f years old' % 14.1
I am 14.1 years old

另一个例子:

def greet(name):
    print 'Hello, %s!'%name

注意!

转换说明符包含两个或多个字符,并具有以下组件,这些组件必须按以下顺序出现:

  • '%'字符,用于标记说明符的开头。
  • 映射键(可选),由带括号的字符序列组成(例如,(somename))。
  • 转换标志(可选),它会影响某些转换类型的结果。
  • 最小字段宽度(可选)。如果指定为'*'(星号),则从值的元组的下一个元素读取实际宽度,并且要转换的对象在最小字段宽度和可选精度之后。
  • 精确(可选),以'。'给出(点)后跟精度。如果指定为'*'(星号),则从值的元组的下一个元素读取实际宽度,并且要转换的值在精度之后。
  • 长度修饰符(可选)。
  • 转换类型。

参考

答案 2 :(得分:0)

它只是告诉Python替换格式化程序部分中的所有%: http://docs.python.org/2/library/stdtypes.html#string-formatting-operations