Shabari nath k
Shabari nath k

Reputation: 890

How to get a specifict part of a string inside a list?

I have a List :

Old_list =['orders_ce_deduped.01.csv','orders_ce_deduped.02.csv']

i need to get the 01 and 02 part and store that into another list using python

new_list = ['01','02']

Upvotes: 1

Views: 91

Answers (4)

Tejas makadia
Tejas makadia

Reputation: 1

Method 1:

Old_list =['orders_ce_deduped.01.csv','orders_ce_deduped.02.csv']
new_list = []

for i in range(len(Old_list)):
      new_list.append(Old_list[i][18:20])
print(new_list)

Method 2: List Comprehension

Old_list =['orders_ce_deduped.01.csv','orders_ce_deduped.02.csv']
new_list = []

[new_list.append(Old_list[i][18:20]) for i in range(len(Old_list))]
print(new_list)

Upvotes: 0

Link
Link

Reputation: 120

If you're specifically looking for the digits within two periods (".XXX."), you can use regular expressions:

import re

Old_list =['orders_ce_deduped.01.csv','orders_ce_deduped.02.csv']

pattern = re.compile(r"\.(\d+)\.")
new_list = [re.findall(pattern, string)[0] for string in Old_list]

print(new_list)

# Output
['01', '02']

Upvotes: 0

SAI SANTOSH CHIRAG
SAI SANTOSH CHIRAG

Reputation: 2084

You can try this:

new_list = []
for i in old_list:
    cur = i.split('.')[-2]
    new_list.append(cur)
print(new_list)
#Output
['01','02']
 

Upvotes: 1

sammy
sammy

Reputation: 437

If your csv file names are consistent like your example('~~~.number.csv')

this would probably work

new_list = [i.split('.')[1] for i in Old_list]

Upvotes: 2

Related Questions