Md. Rezwanul Haque
Md. Rezwanul Haque

Reputation: 2950

Take a specific sub-string from a string in python

How to store lst1 = [26.7,8.2,13.7,8.6,16] from Train_level1 in python?

Train_level1 = ['1_Rehana_Karim_F49_850_GL=26.7','43_G.M.Alauddin Azad_M42_940_GL=8.2','110_Ronojeet_Bishwash_M47_940_GL=13.7','112_Mustafizur_Rahman_M60_850_GL=8.6','123_Farida_Yeasmin_F55_940_GL=16']

Similarly, How to store lst2 = [11.5,12.9,9.2] from Train_level2 in python ?

Train_level2 = ['S140_M75_GL=11.5-850LEDFon_F=110.jpg', 'S85_F56_GL=12.9-940LEDFon_F=105.jpg', 'S108_M71_GL=9.2-850LEDFon_F=100.jpg']

Upvotes: 1

Views: 55

Answers (2)

Patrick Artner
Patrick Artner

Reputation: 51683

You can use regex to parse your numbers:

import re

Train_level1 = ['1_Rehana_Karim_F49_850_GL=26.7',
                '43_G.M.Alauddin Azad_M42_940_GL=8.2',  
                '110_Ronojeet_Bishwash_M47_940_GL=13.7',
                '112_Mustafizur_Rahman_M60_850_GL=8.6',
                '123_Farida_Yeasmin_F55_940_GL=16']

Train_level2 = ['S140_M75_GL=11.5-850LEDFon_F=110.jpg', 
                'S85_F56_GL=12.9-940LEDFon_F=105.jpg', 
                'S108_M71_GL=9.2-850LEDFon_F=100.jpg']


def parseIt(data):
    p1 = r"=(\d+\.?\d*)" # find '=' followed numbers followed by optional '.' + more numbers
    return [float(x[0]) for x in (re.findall(p1,y) for y in data) if x] 


print(parseIt(Train_level1))
print(parseIt(Train_level2))

Output:

[26.7, 8.2, 13.7, 8.6, 16.0]
[11.5, 12.9, 9.2]

The list-comp and regex are identical, hence I created a function for it. They apply the regex to each list-element. You only have one =99.99 element per list so that one we take and change into a float.

Upvotes: 2

galfisher
galfisher

Reputation: 1122

For Train_level, you need to get the number after the =, so we use split() on the list of strings to split it by the = character and get the second string that is in index 0:

lst1 = [float(train.split('=')[1]) for train in Train_level1]

For Train_level2, it's similar, except we need to do two splits - first by = and get the second string (index 1), and then by - and get the first string (index 0):

lst2 = [float(train.split('=')[1].split('-')[0]) for train in Train_level2]

We use float() on the result since split returns a string but the output is a list of numbers, not strings. float will convert a decimal string that contains a number, to a floating point number.

Upvotes: 5

Related Questions