0

I have a string that comes from an input, for example, "ABCD"

I also have multiple strings ("0", "1", "2", "3") that I want to add before each character in "ABCD", such that the final result will be "0A1B2C3D"

I've tried using a dictionary and for loop:

text = input()
if len(text) > 4:
    return
phrases = {0: "0", 1: "1", 2: "2", 3: "3"}
for i in range(len(text)):
    combined = []
    combined[i] = phrases[i] + text[i]
    print(combined[i])

But I get the following error:

IndexError: list assignment index out of range

How do I go about doing this?

yes
  • 3
  • 2

1 Answers1

1

You are clearing out combined during every loop. It never has any elements so even combined[0] is out of range. You need to initialize it outside the loop, and then append the new data. Also, you shouldn't print until you're done with the loop.

text = input()
if len(text) != 4:
    return
phrases = {0: "0", 1: "1", 2: "2", 3: "3"}
combined = ''
for i in range(len(text)):
    combined += phrases[i] + text[i]
print(combined)

Or, better:

for i,c in enumerate(text):
    combined += phrases[i] + c

This could be even simpler if phrases were a list or a string.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30