[英]How can we extract a next numeric value to a string in python
我需要在字符串中取一个 output,例如字符串是“Initial: [818 v1] any other string or words here”,在这里我想从这个字符串中取 818。 这个 818 可以改变,所以不能硬编码。
s = "Initial: [818 v1] any other string or words here"
import re
p = re.findall(r'\d+',s)
print(p)
OUTPUT
['818','1']
但是如果你只想要超过 1 个字符的数字那么
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']
在 OP 想要另一个问题的答案之后。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.