[英]string formatting error when trying to multiply tuple elements - python
If 如果
>>> (1,2)*2
>>> (1,2,1,2)
why isn't this working? 为什么这不起作用?
'%d %d %d %d' % (1,2)*2
TypeError: not enough arguments for format string
Is there another way to do this without having to explicitly construct the tuple? 有没有其他方法可以做到这一点,而无需显式构建元组?
You need to add a pair of parentheses: 您需要添加一对括号:
'%d %d %d %d' % ((1,2)*2)
In Python, %
and *
have the same precedence , so your code is equivalent to 在Python中, %
和*
具有相同的优先级 ,因此您的代码等效于
('%d %d %d %d' % (1,2))*2
The reason the two operators have the same precedence is that %
is also the remainder operator, and thus is considered to be in the same category as multiplication and division. 两个运算符具有相同优先级的原因是%
也是余数运算符,因此被认为与乘法和除法属于同一类别。
Just add an extra pair of parenthesis: 只需添加一对额外的括号:
>>> '%d %d %d %d' % ((1,2)*2)
'1 2 1 2'
>>>
As it currently stands, your code is trying to make the string using (1,2)
and then multiply that string by 2. 就目前而言,您的代码正在尝试使用(1,2)
创建字符串,然后将该字符串乘以2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.