zarek37
zarek37

Reputation: 47

Python extracting a value from a string

Assuming I have this string:

TEST = 'GAMES HELLO VAUXHALL RUNS=15 TESTED=3'

if the text 'RUNS=' exists in TEST, I want to extract the value 15 into a variable, nothing else from that string.

Upvotes: 0

Views: 530

Answers (2)

S.B
S.B

Reputation: 16486

Just split the line and check if one of the items starts with your desired string:

TEST = 'GAMES HELLO VAUXHALL RUNS=15 TESTED=3'

def extract(s: str):
    for i in s.split():
        if i.startswith("RUNS="):
            return int(i.split("=")[1])

print(extract(TEST))

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195438

You can use re module:

import re

s = "GAMES HELLO VAUXHALL RUNS=15 TESTED=3"


m = re.search(r"RUNS=(\d+)", s)
if m:
    print("RUN=... found! The value is", m.group(1))

Prints:

RUN=... found! The value is 15

Upvotes: 1

Related Questions