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.
Asked
Active
Viewed 46 times
0
-
1Does this answer your question? [How to extract numbers from a string in Python?](https://stackoverflow.com/questions/4289331/how-to-extract-numbers-from-a-string-in-python) – Chris May 06 '22 at 12:17
-
why not `1` its also a numeric value – codester_09 May 06 '22 at 12:18
-
2what are the exact rules to select the 818? Can you provide more examples? What is fixed and variable? – mozway May 06 '22 at 12:24
1 Answers
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}

codester_09
- 5,622
- 2
- 5
- 27
-
1
-
-
2I 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 – mozway May 06 '22 at 12:23
-
Yes thanks, it answers the question. I can use RE to extract all numeric value and then use the list to find my useable value. – Sumit Somani May 06 '22 at 12:52
-
@SharimIqbal Thanks! Also can you tell like we I have some specific string and in front of them I have different numeric value, how can we extract that For ex: "Initial: [818 v1] any other string or words here Abc 1 String 2 Xyz 3" So I need a output like {"Abc": 1, "String": 2, "Xyz": 3} – Sumit Somani May 06 '22 at 12:59
-
1
-
@SharimIqbal I think this will be kind of hard coded right, I think may be question was confusing, but let me clarify, it is not necessary that after each string there will be numeric value, there may or may not be, it can be string = 'Abc 1 String Xyz 3 try new 4' so here I need it like {"Abc": 1, "Xyz": 3, "new":4} – Sumit Somani May 06 '22 at 13:12
-
-
1@SumitSomani I know it will take more than a minute But can you check now. – codester_09 May 06 '22 at 13:26