Python:从字符串中过滤正整数和负整数 [英] Python: Filter positive and negative integers from string

查看:776
本文介绍了Python:从字符串中过滤正整数和负整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 3: 给定一个字符串(一个方程式),返回一个正整数和负整数的列表. 我尝试了各种正则表达式和列表理解解决方案,但无济于事.

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.

给出一个方程4 + 3x或-5 + 2y或-7y-2x 返回:[4,3],[-5,2],[-7,-2]

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

输入

str = '-7y-2x'

输出

my_list = [-7, -2]

推荐答案

使用输出:

[-5, 2]


-?\d+-匹配正负整数


-?\d+ - matches positive and negative integers

原始字符串表示法(r"text")使正则表达式保持理智. 没有它,正则表达式中的每个反斜杠('\')都将具有 加上另一个前缀以逃脱它

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

这篇关于Python:从字符串中过滤正整数和负整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆