Home > Blockchain >  Python extracting a value from a string
Python extracting a value from a string

Time:06-11

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.

CodePudding user response:

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

CodePudding user response:

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