3

I keep getting a "cannot concatenate 'str' and 'int' objects" error when I try to run the following code. I'm pointed to line 6 as the source of the problem, but I really can't see the error! My types all seem to be consistent.

def DashInsert(num): 
  num_str = str(num)
  new_str = ''

  for i in num_str:
    var1 = num_str[i:i+1]
    var2 = num_str[i+1:i+2]

    if var1 % 2 == 1 and var2 % 2 == 1:
      new_str = new_str + num_str[i:i+1] + "-"
    else:
      new_str = new_str + num_str[i:i+1]

  return new_str

# keep this function call here  
# to see how to enter arguments in Python scroll down
print DashInsert(raw_input())  
Aylen
  • 3,524
  • 26
  • 36

1 Answers1

7
for i in num_str:

i is not an index in this case, it is a string character.

For example, if num in your code is 42, the work flow will be:

num_str = str(42) # '42'
for i in num_str: # First iteration
    var1 = num_str['4':'4'+1] # Python: '4' + 1 = ERROR

What you are probably looking for is:

for i, c in enumerate(num_str):
    var1 = num_str[0:0+1] # Python: 0 + 1 = 1

See this answer.

Community
  • 1
  • 1
Aylen
  • 3,524
  • 26
  • 36
  • All the answers in that other question just show how to iterate by single characters. But he's trying to access the characters after the current iteration step as well, with his `var1` and `var2` variables. If you don't show how to do that, this is more of a comment than an answer. – Barmar Jun 28 '14 at 03:26