Home > Net >  If there is list of 4 string elements. Several elements are - separated strings. If I want to print
If there is list of 4 string elements. Several elements are - separated strings. If I want to print

Time:09-10

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.

CodePudding user response:

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 != []:
        print(found[0])

Output:

660

CodePudding user response:

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

s = ''.join(list2)

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