簡體   English   中英

如何使用 Python 提取可變長度的子字符串

[英]How to extract sub string of variable length using Python

我通過讀取多行 python 字符串來檢索數據。

我的字符串如下所示:

Hostname: windos
Model: OS_5000
OS: 18.2
OS Kernel 64-bit  [2020_Stable]
....
.....
....

我希望從該字符串中提取 Model 值,即 5000。 不知道該怎么做。

 dpath = op.response()
                    dpath = dpath[dpath.find("Model:")+ 6 : dpath[dpath.find("Model:")+ 11]

此外,model 字符串可以是可變長度的。 有沒有更好的方法呢?

編輯:Model 值可以是數字或非數字。

嘗試:( (using Regex)

import re
s = """Hostname: windos
Model: 5000
OS: 18.2
OS Kernel 64-bit  [2020_Stable]"""
match = re.search('Model: (\d+)', s)
if match:
    print(match.group(1))

5000

如果字符串中有多個Model

import re
s = """Hostname: windos
Model: 5000
OS: 18.2
Model: 12343434
OS Kernel 64-bit  [2020_Stable]"""
match = re.findall('Model: (\d+)', s)
if match:
    print(match)

['5000', '12343434']

您應該嘗試使用正則表達式

import re

re.search('Model: (.*)', dpath).group(1)

使用正則表達式:

import re
model = re.findall('model\:\s*(\d+)', dpath, re.I)
if model:
    model = model[0]

在這里,我使用“re.I”來搜索不區分大小寫的單詞“model”“\s*”——表示冒號后是否有空格,它不會破壞這個腳本。 So it find numbers in next cases: Model: 5000 Model:5000 model: 5000 model: 5000

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM