简体   繁体   中英

Split strings in list

I am creating a list with the files in a folder. The files are named like this: t1507859_Etappe-02-Alpe-Adria-Trail.svg . I want to split the strings to get something like: ["t1507859_Etappe-", "02", "-Alpe-Adria-Trail.svg"] . I want to get back the numbers on the second place of the list I got from the split operation.

dirs = os.listdir (path)

[i.split('-', 2)[1] for i in l]

print dirs

If i parse this code line by line into the python shell it works but not if I let it run as a module. There I just get the normal dir list.

If i parse this code line by line into the python shell it works but not if I let it run as a module. There I just get the normal dir list.

Sure, this is because you are not assigning the result of the list comprehension to a variable . Instead, you meant:

dirs = os.listdir(path)
dirs = [i.split('-', 2)[1] for i in dirs]
print(dirs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM