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

2024-06-01 01:47:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚遇到这个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)前面的%运算符。它是做什么的?我在哪里可以在文档中找到它?

在谷歌上搜索这个,我总是得到模算子。


Tags: and代码文档object语法运算符语句variables
3条回答

'(%g,%g)'是模板,(blank.x,blank.y)是需要填充的值,代替%g%g,而%运算符就是这样做的。它叫做String interpolation or formatting operator

简介

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

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

给定格式%值(格式为字符串或Unicode对象),格式中的%转换规范将替换为零个或多个值元素。其效果与C语言中的using 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))组成。
  • 转换标志(可选),影响某些转换类型的结果。
  • 最小字段宽度(可选)。如果指定为“*”(星号),则从值中元组的下一个元素读取实际宽度,并且要转换的对象位于最小字段宽度和可选精度之后。
  • 精度(可选),以“.”(点)后跟精度给定。如果指定为“*”(星号),则从值中元组的下一个元素读取实际宽度,并且要转换的值在精度之后。
  • 长度修改器(可选)。
  • 转换类型。

参考文献

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

相关问题 更多 >