gpt4 book ai didi

python - 获取 Python 中特殊字符前后的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 11:15:10 24 4
gpt4 key购买 nike

我有以下字符串,我想从该字符串中获取 DDD= 和 % 之间的所有数据

2019-07-25 15:23:13 [Thread-0] DEBUG  - Serial : INFO: QQQ=00000D00001111 AAA=8 BBB=0 CCC=0 DDD=1.08% XXX=2401

我已尝试使用以下代码但无法获得所需的输出

my_string="2019-07-25 15:23:13 [Thread-0] DEBUG  - Serial : INFO: QQQ=00000D00001111 AAA=8 BBB=0 CCC=0 DDD=1.08% XXX=2401"
print(my_string.split("DDD=",1)[1])

得到如下输出

1.08% XXX=2401

但我正在寻找输出为

either 1.08 or 1.08%

请帮帮我

最佳答案

使用正则表达式。

例如:

import re

s = "2019-07-25 15:23:13 [Thread-0] DEBUG - Serial : INFO: QQQ=00000D00001111 AAA=8 BBB=0 CCC=0 DDD=1.08% XXX=2401"
m = re.search(r"DDD=(.*?)%", s) #if you want it to be strict and get only ints use r"DDD=(\d+\.?\d*)%"
if m:
print(m.group(1))

输出:

1.08

关于python - 获取 Python 中特殊字符前后的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57200048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com