简体   繁体   中英

Get string after and before a special Characters in Python

I have following string and from that string I want all the data between DDD= and %

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

I have tried to get use following code but unable to get the desired output

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])

Getting following output

1.08% XXX=2401

But I am looking output as

either 1.08 or 1.08%

Please help me on this

Use Regex.

Ex:

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))

Output:

1.08

Here's an option which uses split twice rather than regex. It's not terribly flexible though and can easily break if the input format changes slightly. You can decide which option is best for your use case.

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"
print(s.split('DDD=')[1].split('%')[0])

Results:

'1.08'

Depending on what you plan to do with the number, you might also want to cast it to a numeric type:

print(float(s.split('DDD=')[1].split('%')[0]))

Results:

1.08

To match all the data between DDD= and % :

import re

test_str = "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=([^%]+)%", test_str)
ddd = m.group(1) if m else m
print(ddd)    # 1.08

Use string find operation:

Example

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"
fst = my_string.find("DDD=")
snd = my_string.find("%")
if fst >= 0 and snd >= 0
    print(my_string[fst+4,snd])

Output

1.08

Or you can use split:

Example

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"
(fst,snd) = my_string.split("DDD=");
(trd,fourth) = snd.split("%");
print(trd)

Output

1.08
    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"
    output1 = print(my_string.split("DDD=")[1][:5])
    #output1  =1.08%
    #output2 = print(my_string.split("DDD=")[1][:4])
    #output2  =1.08

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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