[英]Python: Filter positive and negative integers from string
Python 3:給定一個字符串(一個方程),返回一個正整數和負整數的列表。 我嘗試了各種正則表達式和列表理解解決方案,但無濟於事。
給定一個方程 4+3x 或 -5+2y 或 -7y-2x 返回:[4,3], [-5,2], [-7,-2]
輸入
str = '-7y-2x'
輸出
my_list = [-7, -2]
使用re.findall函數的簡單解決方案:
import re
s = '-5+2y'
result = [int(d) for d in re.findall(r'-?\d+', s)]
print(result)
輸出:
[-5, 2]
-?\\d+
- 匹配正負整數
原始字符串表示法 (
r"text"
) 使正則表達式保持理智。 沒有它,正則表達式中的每個反斜杠 ('\\
') 都必須以另一個反斜杠為前綴才能轉義它
這個正則表達式應該可以解決你的問題。
[\+\-]?[0-9]+
此外,這里有一些與之配套的代碼。
import re
regex = re.compile(r'[\+\-]?[0-9]+')
nums = [int(k) for k in regex.findall('5-21x')]
這是更完整的答案,但保留那些帶有字母的答案。
ss='5 a 2b -13 c2 d2e 111 5.2 .3 1.4x 2223.'
刪除整數和負數(即使在字符串的開頭)
ss1= re.sub(r"(^|\\s)-?(\\d+)\\.?(\\d*)(\\s)", " ", ss)
>>' a 2b c2 d2f 5.2 .3 1.4x 2223.'
去除小數
ss2= re.sub("(^||\\d+)\\.(\\d+) ",'',ss1)
>> ' a 2b c2 d2e 1.4x 2223.'
用 刪除句子末尾的數字。
ss3= re.sub("[0-9+]\\.?(\\d+)(\\.)",' ',ss2)
>> ' a 2b c2 d2e 1.4x '
刪除字符串末尾的數字
ss4= re.sub("[0-9+]\\.?(\\d+)($)",' ',ss3)
>> ' a 2b c2 d2e 1.4x '
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.