Python: Filter positive and negative integers from string

☆樱花仙子☆ 提交于 2020-01-13 07:29:07

问题


Python 3: Given a string (an equation), return a list of positive and negative integers. I've tried various regex and list comprehension solutions to no avail.

Given an equation 4+3x or -5+2y or -7y-2x Returns: [4,3], [-5,2], [-7,-2]

input

str = '-7y-2x'

output

my_list = [-7, -2]

回答1:


Simple solution using re.findall function:

import re

s = '-5+2y'
result = [int(d) for d in re.findall(r'-?\d+', s)]

print(result)

The output:

[-5, 2]

-?\d+ - matches positive and negative integers

Raw string notation (r"text") keeps regular expressions sane. Without it, every backslash ('\') in a regular expression would have to be prefixed with another one to escape it




回答2:


This regex should solve your problem.

[\+\-]?[0-9]+

Also, here is some code that goes with it.

import re
regex = re.compile(r'[\+\-]?[0-9]+')
nums = [int(k) for k in regex.findall('5-21x')]


来源:https://stackoverflow.com/questions/42751063/python-filter-positive-and-negative-integers-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!