0

I have a function which creates a compound string based on how many times the user wants to input the string:

def string_maker(string_list, repeat_list):
  final_string = ''
  for i in range(len(string_list)):
    for _ in range(repeat_list[i]):
      final_string += string_list[i]
  return final_string

So, for example, string_maker(['a', 'b', 'c'], [1, 2, 1]) outputs abbc.

I want to make it so that if the user doesn't input a list for the repeat_list argument, it defaults to all 1s. This is how I'm trying to do it:

def string_maker(string_list, repeat_list = None):
  if repeat_list == None:
    repeat_list = [1] * len(string_list)
  final_string = ''
  for i in range(len(string_list)):
    for _ in repeat_list[i]:
      final_string += str
  return final_string

print(string_maker(['a', 'b', 'c']))

However, I receive an error saying 'int' object is not iterable, even though the new snippet I included returns the appropriate list [1, 1, 1]. Is there a better way to go about doing this?

4
  • 1
    Just to note that your inner loop isn't using range as you did originally... Commented Mar 25, 2020 at 22:07
  • 1
    The variable (?) str is undefined in the second code snippet (it's the name of a built-in class, so you shouldn't be using it a variable name in the first place). Commented Mar 25, 2020 at 22:10
  • The problem is this line: for _ in repeat_list[i]:... repeat_listp[i] will be an int object, and you cannot iterate over int object, as the error clearly states. Commented Mar 25, 2020 at 22:15
  • Thanks everything, this was a terrible example of my not being able to copy and paste my own code properly... Commented Mar 25, 2020 at 22:39

1 Answer 1

2

The join method is a much more efficient way to build this list.

from itertools import repeat


def string_maker(string_list, repeat_list=repeat(1)):
    return ''.join([x*n for x, n in zip(string_list, repeat_list)])

repeat(1) provides an infinite stream of 1s; zip only uses as many of them as it needs to pair with elements of string_list. x*n creates a string consisting of n repeated occurrences of x.

>>> string_maker(list("abc"))
'abc'
>>> string_maker(list("abc"), [1,2,1])
'abbc'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.