簡體   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