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

seb*_*seb 8 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))
Run Code Online (Sandbox Code Playgroud)

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

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

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

Ans*_*shi 8

介绍

%字符串在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.
Run Code Online (Sandbox Code Playgroud)

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

string%values #where string is a str or unicode and values is a dict or a single value
Run Code Online (Sandbox Code Playgroud)

例子

>>> 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
Run Code Online (Sandbox Code Playgroud)

另一个例子:

def greet(name):
    print 'Hello, %s!'%name
Run Code Online (Sandbox Code Playgroud)

警告!

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

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

参考


the*_*eye 7

'(%g,%g)'为模板,(blank.x,blank.y)都是需要到位的要填充的值%g,并%g%运营商做到了这一点.它叫做String插值或格式化运算符.