Python Forum

Full Version: split the list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I have below code to split the list and get the last element as the file name.
but when I access the last element after splitting, its is not giving me the last element.

post_fix = ['D/Raj_Data/PythonCodes','/C/Viru_Data/PythonCodes']
for i in range(len(post_fix)):
    tmp = str((post_fix[i])[:-1])
    #print(tmp)
    print((str(post_fix[i].split('/')))[:-1])
when I print as below:
my_file[:-1]
Out[25]: "['', 'D', 'Mekala_Backupdata', 'PythonCodes"
remove the slice:
post_fix = ['D/Raj_Data/PythonCodes','/C/Viru_Data/PythonCodes']
for i in range(len(post_fix)):
    tmp = str((post_fix[i]))
    #print(tmp)
    print((str(post_fix[i].split('/'))))
It's not pythonic to get index and then use this index to access item in list. Pythonic way is to iterate over items directly.

There is also .rsplit which (as far as I can understand) is suitable for achieving desired result:

>>> post_fix = ['D/Raj_Data/PythonCodes','/C/Viru_Data/PythonCodes']
>>> for item in post_fix:
...     print(item.rsplit('/', maxsplit=1)[1])
... 
PythonCodes
PythonCodes