Home > OS >  Print a part of stream-string?
Print a part of stream-string?

Time:02-21

How can I print what's after a colon like 's':, 'E':, or 'p': by giving the symbol as reference? I tried this based on all what I know so far but I get a weird error:

        XXXX = f"{{'stream': 'ABCDEF', 'data': {{'s': 'ABC', 'E': 1123, 'p': '0.0',  'q': '0.0'}}}}"
        print(XXXX)
        print(XXXX['data']['p'])

Output:

{'stream': 'ABCDEF', 'data': {'s': 'ABC', 'E': 1123, 'p': '0.0',  'q': '0.0'}}
Error: in main: print(XXXX['data']['p'])
       TypeError: string indices must be integers

CodePudding user response:

By using ast module, you can simply do what you need:

import ast
XXXX = f"{{'stream': 'ABCDEF', 'data': {{'s': 'ABC', 'E': 1123, 'p': '0.0',  'q': '0.0'}}}}"
myDict = ast.literal_eval(XXXX)
print(myDict["data"]["p"])

Output

'0.0'

CodePudding user response:

Since XXXX is a string and the example you provided is a json that you want to convert i would sugest the following:

import json

#replace the single quote for double quote in order to parse the json string
x = json.loads(XXXX.replace("'", '"'))

#print the dictionary key you wanted
print(x['data']['p'])

This works as expected for the given input. If you have any other samples that differ from the one provided please let me know.

  • Related