简体   繁体   中英

I want to know a better way to replace() Python

How can I get a better way? josn :

home = '{u'1p': u'2', u'2p': u'0', u'rs': u'2', u'3p': u'0', u'penalty': u'0', u'fe': u'2', u'ord': u'2', u'ot':u'0'}'

I want the result.

home = '1p: 2, 2p: 0, rs: 2, 3p: 0, penalty: 0, fe: 2, ord: 2, ot:0'

I tried this.

home= sport.get("home")
home= str(home).replace("{","")
home= str(home).replace("}","")
home= str(home).replace("u'","")
home= str(home).replace("'","")
import json
d = json.loads(home)
print(','.join('%s: %s' % tup for tup in d.items()))

You can use ast.literal_eval()

res = ''.join('{}: {}, '.format(k, v) for k, v in ast.literal_eval(home).items())[:-2]

Output:

>>> res
'1p: 2, 2p: 0, rs: 2, 3p: 0, penalty: 0, fe: 2, ord: 2, ot: 0'

So, time for some string magic:

home = "{u'1p': u'2', u'2p': u'0', u'rs': u'2', u'3p': u'0', u'penalty': u'0', u'fe': u'2', u'ord': u'2', u'ot':u'0'}"
import ast
home = ''.join(['{}: {}, '.format(k,v) for k,v in ast.literal_eval(home).items()]).strip(', ')

This will land you with home = '1p: 2, 2p: 0, rs: 2, 3p: 0, penalty: 0, fe: 2, ord: 2, ot: 0'

But in essence, this is a one-line workaround for doing the exact same thing you were doing with the replaces. It converts the string home to a dictionary to use in a comprehension. In the end, the dictionary is replaced by a string. I do not see what the use would be for removing a piece of structure engrained in the json, except if it is for printing purposes, which can be done more efficiently in a dict comprehension.

You could use regex

home = sport.get("home")
home = re.sub(r'[{}\'u]+','', home)

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