1

I am trying to create a string separated by comma from the below given list

 ['D:\\abc\\pqr\\123\\aaa.xlsx', 'D:\\abc\\pqr\\123\\bbb.xlsx', 'D:\\abc\\pqr\\123\\ccc.xlsx']

New string should contain only the filename like below which is separated by comma

'aaa.xlsx,bbb.xlsx,ccc.xlsx'

I have achieved this using the below code

n = []        
for p in input_list:
    l = p.split('\\')
    l = l[len(l)-1]
    n.append(l)
a = ','.join(n)
print(a)

But instead of using multiple lines of code i would like to achieve this in single line using a list comprehension or regular expression.

Thanks in advance...

2 Answers 2

5

Simply do a

main_list = ['D:\\abc\\pqr\\123\\aaa.xlsx', 'D:\\abc\\pqr\\123\\bbb.xlsx', 'D:\\abc\\pqr\\123\\ccc.xlsx']

print([x.split("\\")[-1] for x in main_list])

OUTPUT:

['aaa.xlsx', 'bbb.xlsx', 'ccc.xlsx']

In case u want to get the string of this simply do a

print(",".join([x.split("\\")[-1] for x in main_list]))

OUTPUT:

aaa.xlsx,bbb.xlsx,ccc.xlsx

Another way to do the same is:

print(",".join(map(lambda x : x.split("\\")[-1],main_list)))

OUTPUT:

aaa.xlsx,bbb.xlsx,ccc.xlsx

Do see that os.path.basename is OS-dependent and may create problems on cross-platform scripts.

Sign up to request clarification or add additional context in comments.

Comments

2

Using os.path.basename with str.join

Ex:

import os
data = ['D:\\abc\\pqr\\123\\aaa.xlsx', 'D:\\abc\\pqr\\123\\bbb.xlsx', 'D:\\abc\\pqr\\123\\ccc.xlsx']
print(",".join(os.path.basename(i) for i in data))

Output:

aaa.xlsx,bbb.xlsx,ccc.xlsx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.