Ulderique Demoitre
Ulderique Demoitre

Reputation: 1068

Add automatically the quotation marks inside a string in python

I am in python and I want to add the quotation marks inside a string. Concretely, I have the following string:

'{name:robert,surname:paul}'

And I want to programmatically get the following, operating on the first

'{name:"robert",surname:"paul"}'

Is there any efficient way to perform this?

Upvotes: 5

Views: 2106

Answers (2)

uspectaculum
uspectaculum

Reputation: 402

def literalize(string):
    string = string[1:-1].split(',')
    string = map(lambda s: str.split(s, ':'), string)
    return_string = ''
    for item in string:
            return_string += '%s: "%s", ' % tuple(item)
    return "{%s}" % return_string

I wouldn't ever consider this a masterpiece but I've tried not to use RegEx for this; however it ended up being messy and bodgy, and obviously factorizable with list comprehensions and what not.

Some implementation details are that it won't work very well when the value has a comma or colon inside, and another implementation detail being that tuple(item) can be replaced by (*item) if you prefer a more Python 3 way.

 >>> literalize(a)
'{name: "robert", surname: "paul", }'

Note: I don't think the redundant , at the end should matter too much when parsing using something like json.loads(...)

Upvotes: 0

Indent
Indent

Reputation: 4967

Use a regex to match word \w* after : and replace it using backreference \1 :

Prefix your regexstring by r (raw string) to automatically escape characters.

https://repl.it/Nh29/1

import re

input_str='{name:robert,surname:paul}'

output_str=re.sub(r':(\w*)', r':"\1"', input_str )

print output_str

will produce

{name:"robert",surname:"paul"}

Upvotes: 9

Related Questions