繁体   English   中英

从字符串中提取整数

[英]Extract integers from a string

如何从字符串中找到一些整数。 并将它们存储在列表中。

这是我的示例字符串:

--- +++ @@ -8 ,7 +8 ,7 @@ 识别轨道: "10" 系统检查@@ -17 ,7 +17 ,7 @@@@ -31 ,7 +31退出服务器,7 @@ 开始开发 : 526 server at ---@@ -41 ,7 +41 ,7 @@ 文件更改与 StatReloader

我要提取的整数将来自 @@ -X,7 +X,7 @@,其中 X 是要提取的整数。

所以输出将是:

[8, 17, 31, 41]

使用正则表达式。

前任:

import re

s = """--- +++ @@ -8,7 +8,7 @@ identified track: "10" System check @@ -17,7 +17,7 @@ Quit the server with @@ -31,7 +31,7 @@ Starting development : 526 server at ---@@ -41,7 +41,7 @@ file changes with StatReloader"""
print(re.findall(r"@@ -(\d+)", s))
# --> ['8', '17', '31', '41']

您可以为此使用正则表达式:

import re
result = re.findall(r'(\d+),')

如果您不需要重复项:

result = set(result)

在此处阅读有关 Python re 模块的更多信息。

import re
print(re.findall(r"(\-\d+)|(\+\d+)", "[string you want]"))

[string you want]的字符串[string you want]更改为您的字符串...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM