简体   繁体   中英

How to strip everything but the first 2 characters for each item in a list?

I'm using a list generated from from a directory containing multiple config files. All the config files follow the same naming convention, they start with two letters, followed by 2-3 numbers and end in.conf

aa01.conf, aa02.conf, aa03.conf, bb01.conf, bb02.conf,...zz99.conf, zz100.conf

I am only interested in the two letters at the start of the each file. How do I strip the numbers, the '.conf', and then remove all duplicates from the result?

If you only want the first two characters:

list_1 = ['aa01.conf', 'aa02.conf', 'aa03.conf', ... 'zz99.conf', 'zz100.conf']
list_2 = [item[:2] for item in list_1]

To remove the duplicates

list_3 = list(set(list_2))

to have first two chars and extension, you can do something like this

your_list = ["aa01.conf", "aa02.conf", "aa03.conf", "bb01.conf", "bb02.conf"]

your_list_with_out_duplicates = list(set(your_list))
your_lis_of_first_two_char = [
    f"{x[:2]}.{x[-4:]}" for x in your_list_with_out_duplicates
]
print(your_lis_of_first_two_char)

output

['bb.conf', 'aa.conf', 'aa.conf', 'aa.conf', 'bb.conf']

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