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())
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With