Python 从拆分句中查找整数和字符串
我需要拆分此字符串:Python 从拆分句中查找整数和字符串,python,string,python-2.7,python-3.x,Python,String,Python 2.7,Python 3.x,我需要拆分此字符串: "We shall win 100 dollars in the next 2 years" 返回一个包含整数和字符串列表的元组([100,2],[We,Well,win,dollars,in,the,next,years]) 我迄今为止的努力: lst_int =[] lst_str =[] tup_com =(lst_int,lst_str) words = input_string.split() for i in words:
"We shall win 100 dollars in the next 2 years"
返回一个包含整数和字符串列表的元组([100,2],[We,Well,win,dollars,in,the,next,years])
我迄今为止的努力:
lst_int =[]
lst_str =[]
tup_com =(lst_int,lst_str)
words = input_string.split()
for i in words:
if i == int():
lst_int.append(i)
elif i != int():
lst_str.append(i)
return tup_com
您可以使用以下几种方法进行此操作: 1) 检查
isdigit
:
sentence = "We shall win 100 dollars in the next 2 years"
str_list=[]
int_list=[]
for word in sentence.split():
if word.isdigit():
int_list.append(int(word)) # cast at the same time
else:
str_list.append(word)
问题:如果数字为负数,则必须检查是否包含减号、空格字符,这些数字仍然被视为有效数字,这使得isdigit
的操作更加复杂。这可能会导致您找到一个更复杂的正则表达式,它会打开潘多拉的盒子,使用正则表达式解析整数。。。(我甚至没有提到浮点数)
2) 依赖python整数解析:
str_list=[]
int_list=[]
for word in sentence.split():
try:
int_list.append(int(word))
except ValueError:
str_list.append(word)
由于异常处理,速度稍慢,但在所有情况下都可以正常工作,甚至可以推广到浮点运算。如果稍微调整一下条件,就可以实现这一点
i==int()
并没有真正做到你所想的int()
相反,在for
循环中使用str.isdigit
,如下所示:
if i.isdigit():
lst_int.append(i)
else:
lst_str.append(i)
str.isdigit
遍历您提供的字符串中的字符,并计算它们是否都是数字(且字符串非空)
然后,tup\u com
会产生以下结果:
(['100', '2'], ['We', 'shall', 'win', 'dollars', 'in', 'the', 'next', 'years'])
另外,这里不需要tup\u com
,只需返回用逗号分隔的列表,就可以创建包含它们的元组
即:
return lst_int, lst_str
你可以用简单的正则表达式
import re
s = "We shall win 100 dollars in the next 2 years"
t = (re.findall("[0-9]+",s),re.findall("[a-zA-Z]+",s))
非常感谢您的精彩解释。谢谢您,先生!另一个很棒的方法。谢谢!