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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.