我们如何将下一个数值提取到 python 中的字符串
How can we extract a next numeric value to a string in python
我需要一个字符串形式的输出,比如 string is
“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)
输出
['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)
输出:
['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)
我需要一个字符串形式的输出,比如 string is “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)
输出
['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)
输出:
['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)