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

后端 未结 5 846
Happy的楠姐
Happy的楠姐 2020-12-03 03:16

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

5条回答
  •  有刺的猬
    2020-12-03 04:08

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

提交回复
热议问题