If there is list of 4 string elements. Several elements are - separated strings. If I want to print just one part of the - separated word

Viewed 44
list2 = ['BIA-660', 'Web', 'Analytics']

Question: How to extract "660" from list2

list2 = ['BIA-660', 'Web', 'Analytics']
c=list2[0]
x=c.split("-")
print(x[1])

I am getting the answer but Wanted to know if there is another more efficient way of achieving the solution.

3 Answers

You could use Regex to get any digits from a string

import re

list2 = ['BIA-660', 'Web', 'Analytics']

for strg in list2:
    found = re.findall('\d+', strg)
    if found != []:
        for num in found:
            print(num)

Output:

660

This will return a list of numbers contained in the string:

list2 = ['BIA-660', 'Web', 'Analytics']
s = '-'.join(list2)

# extract numbers from string
result = [int(txt) for txt in s.split('-') if txt.isdigit()]
print(result)

[660]

I find with these things it can be important to get the result but also know where the result came from. So, all as well as returning the data, it tells where the index it was found at in the input list.

Also takes into account Several occurences of -separated items, as well as something like foo-bar-zoom.

def extractor(li : list[str]) -> list[tuple[str,int]]:

    res = []
    for ix, v in enumerate(li):
        if "-" in v:
            found = v.split('-',maxsplit=1)[1]
            res.append((found,ix))

    return res

Some runs:

✅! 
extractor for ['BIA-660', 'Web', 'Analytics']                                                                      
exp :[('660', 0)]:
got :[('660', 0)]:

✅! 
extractor for ['BIA-660', 'Web-3.0', 'Analytics']                                                                  
exp :[('660', 0), ('3.0', 1)]:
got :[('660', 0), ('3.0', 1)]:

✅! 
extractor for ['BIA-660', 'foo-bar-zoom']                                                                          
exp :[('660', 0), ('bar-zoom', 1)]:
got :[('660', 0), ('bar-zoom', 1)]:


You could extend it to ignore list items that are not strings (isinstance(v,str)) and extracted values that are not numbers (check that float(found) succeeds).

Related