开发者

Multiplying a string with a number results in "TypeError: can't multiply sequence by non-int of type 'str'"

开发者 https://www.devze.com 2023-01-13 00:45 出处:网络
I need a string consisting of a repetition of a particular character. At the Python console, if I type:

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

n = '0'*8

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

But, if开发者_运维百科 I have the same in a Python program (.py file), then the program aborts with an error saying

can't multiply sequence by non-int of type 'str'

Any way to fix this?


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

>>> '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'


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.


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'
>>>


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']


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消