0

There is a need that I have a taken a output in a string such as string is "Initial: [818 v1] any other string or words here" and here I want to take 818 from this string. This 818 can change so can't hard code it.

3
  • 1
    Does this answer your question? How to extract numbers from a string in Python? Commented May 6, 2022 at 12:17
  • why not 1 its also a numeric value Commented May 6, 2022 at 12:18
  • 2
    what are the exact rules to select the 818? Can you provide more examples? What is fixed and variable? Commented May 6, 2022 at 12:24

1 Answer 1

1

s = "Initial: [818 v1] any other string or words here"

import re
p = re.findall(r'\d+',s)
print(p)

OUTPUT

['818','1']

But if you only want the number which has more than 1 character Then

s = "Initial: [818 v1] any other string or words here"

import re
p = re.findall(r'\d+',s)
p = list(filter(lambda e:len(e)-1,p))
print(p)

OUTPUT:

['818']

After OP wants another question answer.

string = 'Abc 1 String Xyz 3 try new 4'

string_lst = string.split()

def func(lst,e):
    if not lst[e].isdigit():
        try:
            int(lst[e+1])
        except IndexError:
            return lst[e]
        except ValueError:
            return False
        else:
            return lst[e]
    return lst[e]

lst = [func(string_lst,a) for a in range(len(string_lst))]

string_list = list(filter(lambda e:e,lst))

string_dict = {string_list[a]:int(string_list[a+1]) for a in range(0,len(string_list),2)}
print(string_dict)

Or you can try this way


import re

s = 'Abc 1 String Xyz 3 try new 4'

matches = re.findall(r'(\w+)\s*(\d+)?', s)
result = {key: int(value) for key, value in matches if value}

print(result)

OUTPUT

{'Abc': 1, 'Xyz': 3, 'new': 4}
Sign up to request clarification or add additional context in comments.

9 Comments

I don't think the 1 is wanted
@mozway check now.
I don't think I'd do it this way, you can avoid selecting the 1 in the first place, but the question is too ambiguous at the moment to really know what is expected
@SumitSomani Check now.
@SumitSomani I know it will take more than a minute But can you check now.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.