简体   繁体   English

尝试乘以元组元素时字符串格式错误 - python

[英]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.

相关问题 Python-格式化元组/字符串 - Python - formatting a tuple/string Python 列表元素与转换为元组以进行字符串格式化 - Python list elements vs converting to tuple for string formatting 如何在python中的元组元素之间进行除法或乘法? - How to divide or multiply between elements of a tuple in python? 当尝试在循环中乘以矩阵元素时,错误“只有长度为1的数组可以转换为Python标量”? - The error “only length-1 arrays can be converted to Python scalars” when trying to multiply matrix elements within a loop? "在 Python 中使用字符串格式打印元组" - Printing tuple with string formatting in Python TypeError:在字符串格式化期间并非所有参数都转换为元组python中的错误 - TypeError: not all arguments converted during string formatting Error in tuple python 在 Python 中格式化字符串时出现“IndexError:元组索引超出范围” - “IndexError: tuple index out of range” when formatting string in Python 在Python中将元组转换为字符串时出错 - Error when converting tuple to string in Python 尝试在 Python 中使用 cursor.executemany(string, tuple) 时引发 SQLite 操作错误 - SQLite operational error is raised when trying to use cursor.executemany(string, tuple) in Python 尝试乘以变量时出错? - Error when trying to multiply a variable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM