Pythonā€™s isalpha() seems inconsistent | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 1

Pythonā€™s isalpha() seems inconsistent

I was doing the Spy Message challenge and while using the isalpha() method I noticed that some numbers are removed and others arenā€™t, is this a problem with the method or using it incorrectly. In the attached code it uses two examples from the challenge where the first one works correctly and the second doesnā€™t. https://code.sololearn.com/cOl1ACV6GiYz/?ref=app Edit: Ipang is completely right an shouldnā€™t do this if itā€™s possible to avoid it, however I did it anyways and got it to work, solved in comments

26th Jul 2021, 11:11 PM
VenomousHamsterX
4 Respostas
+ 6
Basically, the idea of removing item from an iterable while iterating it is a bad idea. Index no longer point to a valid item once an item had been removed from an iterable, as the size of the iterable had changed. Your first sample won't work either had there been spaces. You might be better off to use filter() or comprehension with condition applied to get rid of unwanted characters.
26th Jul 2021, 11:29 PM
Ipang
+ 2
Adding to what Ipang said , you can use regex as well! import re new_msg=re.sub("[^a-z]","","".join(msg))
26th Jul 2021, 11:43 PM
Abhay
Abhay - avatar
27th Jul 2021, 12:31 AM
VenomousHamsterX
0
VenomousHamsterX Here's a possible solution: print("".join(x for x in input() if x == " " or x.isalpha())[::-1]) # Hope this helps
27th Jul 2021, 8:06 AM
Calvin Thomas
Calvin Thomas - avatar