python 3.x - Changing string to int from a list of lists only for isdigit -


i have list called rawsafirlistoflists , work python 3, looking this:

[['423523525', 'horos', 'wafad', ' 23523523523 - horod wafad', 'august', '2014', '540', '0', 'ianuarie', '2015', '0', '0', 'restanta_mandat', 'mandat neachitat nam', '', 'ajutor refugiati', 'inclus_in_plata', ''], ['5235232', 'stoicovicidf', 'pauladd andreead', ' 52352352352 - stoicovicide paulf cristian', 'august', '2014', '42', '0', 'februarie', '2015', '0', '0', 'restanta_mandat', '', '', 'alocatia de stat pentru copii', 'inclus_in_plata', '']] 

there want iterate , transform numbers string int. code:

for level1 in rawsafirlistoflists: level2 in level1:     if level2.isdigit():         int(level2)         print(level2) print (rawsafirlistoflists) 

when print level2 see if had found right string (the ones numbers) , converted them in int wanted, isn't saving change. problem @ end when print list rawsafirlistoflists values unchanged (all indexes remained strings), how can push modifications @ if statement values remain int?

using str.isdigit right approach, int(level2) doing nothing (useful). call int returns integer value discard, not mutate string level2. (in fact, strings don't have mutating methods on them.)

in order fix approach (after fixing indentation), create new list append return values of calls int (or original value, in case str.isdigit returns false).

this done list comprehension follows.

>>> mylist = ['123', 'not-an-int', '456'] >>> converted = [int(x) if x.isdigit() else x x in mylist] >>> converted [123, 'not-an-int', 456] 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -