Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 628
Abhimanyu Agarwala Avatar asked Jan 22 '26 03:01

Abhimanyu Agarwala


2 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
like image 95
Black Raven Avatar answered Jan 25 '26 20:01

Black Raven


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]
like image 35
Sy Ker Avatar answered Jan 25 '26 19:01

Sy Ker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!