Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
split the list
#1
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"
Reply
#2
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('/'))))
Reply
#3
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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] why can't i create a list of numbers (ints) with random.randrange() astral_travel 7 1,455 Oct-23-2022, 11:13 PM
Last Post: Pedroski55
  Split string using variable found in a list japo85 2 1,238 Jul-11-2022, 08:52 AM
Last Post: japo85
  [split] question about list comprehension Armin 17 5,531 Jan-29-2020, 04:32 PM
Last Post: Clunk_Head
  List help to split into single entries paul41 3 2,198 Nov-25-2019, 08:09 AM
Last Post: perfringo
  Split the list and obtain a single value Gururaj 1 2,096 Jul-12-2019, 12:01 AM
Last Post: scidam
  [split] Automate the boring stuff, inserting commas in list srikanth 1 2,079 Jul-02-2019, 02:29 PM
Last Post: metulburr
  Split List and Sublist from Pyodbc parthi1705 1 2,203 May-05-2019, 10:44 AM
Last Post: Larz60+
  split a item from a list frequency 2 2,610 Nov-03-2018, 12:57 PM
Last Post: frequency

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020