在python中将字符串与数字相乘

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3536996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:37:26  来源:igfitidea点击:

Multiplying a string with a number in python

python

提问by Paul

I need a string consisting of a repetition of a particular character. At the Python console, if I type :

我需要一个由特定字符的重复组成的字符串。在 Python 控制台,如果我输入:

n = '0'*8

then n gets assigned a string consisting of 8 zeroes, which is what I expect.

然后 n 被分配了一个由 8 个零组成的字符串,这正是我所期望的。

But, if I have the same in a Python program (.pyfile), then the program aborts with an error saying
can't multiply sequence by non-int of type 'str'

但是,如果我在 Python 程序(.py文件)中有相同的内容,则程序会中止并显示错误
can't multiply sequence by non-int of type 'str'

Any way to fix this ?

有任何解决这个问题的方法吗 ?

回答by Jo?o Pinto

That line of code works fine from a .py executed here, using python 2.6.5, you must be executing the script with a different python version.

这行代码从这里执行的 .py 中运行良好,使用 python 2.6.5,您必须使用不同的 python 版本执行脚本。

回答by Jo?o Pinto

You get that error because - in your program - the 8 is actually a string, too.

您会收到该错误,因为 - 在您的程序中 - 8 实际上也是一个字符串。

>>> '0'*8
'00000000'
>>> '0'*'8' # note the ' around 8
(I spare you the traceback)
TypeError: can't multiply sequence by non-int of type 'str'

回答by kirbuchi

I could bet you're using raw_input()to read the value which multiplies the string. You should use input()instead to read the value as an integer, not a string.

我敢打赌,您正在使用raw_input()读取乘以字符串的值。您应该改用input()将值读取为整数,而不是字符串。

回答by jabbas

The reason that you are getting the error message is that you're trying to use multiplying operator on non integer value.

您收到错误消息的原因是您试图对非整数值使用乘法运算符。

The simplest thing that will do the job is this:

完成这项工作的最简单的事情是:

>>> n = ''.join(['0' for s in xrange(8)])
>>> n
'00000000'
>>>

Or do the function for that:

或者为此执行以下功能:

>>> def multiply_anything(sth, size):
...     return ''.join(["%s" % sth for s in xrange(size)])
...
>>> multiply_anything(0,8)
'00000000'
>>>

回答by LAS

If you want the result to be a list of strings instead of a single one, you can always use this:

如果您希望结果是一个字符串列表而不是单个字符串,您可以随时使用:

list(('0',) * 8)

And you can get:

你可以得到:

['0', '0', '0', '0', '0', '0', '0', '0']