+ 1

Why is this code producing no output?

I’m curious why this code is producing no output from either of the two print statements. I suspect it has to do with my while/if statements. If I comment them out I suddenly get output, but no idea why. I’m trying to find capital letters and insert an ‘_’ before them. https://code.sololearn.com/cpXGlP9XW0EA/?ref=app

21st Feb 2020, 6:30 AM
Nate Toon
Nate Toon - avatar
9 ответов
+ 4
The reason you're not getting output is because the loop doesn't end. re.match(r'[A-Z]',list[i]) is always true, because when you insert '_' to list, the underscore is inserted in front of the list. Incrementing i by 1 will then cause re.match to evaluate 'B' on the next iteration. Remember that len(list) is also incrementing. As a result, you are incrementing both i and len(list), and i will never be >= len(list). T̶r̶y̶ ̶d̶o̶i̶n̶g̶ ̶l̶i̶s̶t̶.̶a̶p̶p̶e̶n̶d̶ ̶i̶n̶s̶t̶e̶a̶d̶,̶ ̶w̶h̶i̶c̶h̶ ̶a̶p̶p̶e̶n̶d̶s̶ ̶t̶h̶e̶ ̶t̶a̶r̶g̶e̶t̶ ̶e̶l̶e̶m̶e̶n̶t̶ ̶t̶o̶ ̶t̶h̶e̶ ̶e̶n̶d̶ ̶o̶f̶ ̶t̶h̶e̶ ̶l̶i̶s̶t̶.̶ ̶ ̶l̶i̶s̶t̶.̶a̶p̶p̶e̶n̶d̶(̶'̶_̶'̶)̶ My bad - Didn't read the thread entirely.
21st Feb 2020, 6:36 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
Nate Toon Ye know since you're using re anyway, there's a much better way to do this using re.sub if you're interested.
21st Feb 2020, 6:42 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
Nate Toon import re word = "BosTon" word = re.sub("([A-Z])", "_\g<1>", word) # if you still need to do this ofc list = list(word) print(list)
21st Feb 2020, 6:46 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
list.append won’t insert the _ where I need it but I changed i += 2 for my if statement and now it bypasses! thanks a million!
21st Feb 2020, 6:40 AM
Nate Toon
Nate Toon - avatar
+ 1
See comment in code
21st Feb 2020, 6:36 AM
Oma Falk
Oma Falk - avatar
+ 1
Nate Toon ok... does the job!
21st Feb 2020, 6:42 AM
Oma Falk
Oma Falk - avatar
+ 1
Hatsy Rei yea, I’m all ears
21st Feb 2020, 6:43 AM
Nate Toon
Nate Toon - avatar
+ 1
Hatsy Rei I like that a lot thanks again!
21st Feb 2020, 6:55 AM
Nate Toon
Nate Toon - avatar
0
It indicates bos_ton because in this code you increase the index number by 1 then by 2 so as u write print(i,'_') so python print _ at 3 index
23rd Feb 2020, 3:55 AM
Aryan Sharma
Aryan Sharma - avatar