简体   繁体   English

在python中自动添加字符串内的引号

[英]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. 我在python中,我想在字符串中添加引号。 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? 有没有有效的方法来执行此操作?

Use a regex to match word \\w* after : and replace it using backreference \\1 : 使用正则表达式匹配单词\\w*:并使用反向引用\\1替换它:

Prefix your regex string by r (raw string) to automatically escape characters. r (原始字符串)前缀你的regex字符串以自动转义字符。

https://repl.it/Nh29/1 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"}
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; 我不会认为这是一个杰作,但我试图不使用RegEx这个; 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. 一些实现细节是,当value内部有逗号或冒号时,它将无法正常工作,另一个实现细节是,如果您更喜欢Python 3方式,则可以用(*item)替换tuple(item)

 >>> 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(...) 注:我不认为多余的,在结束使用类似的分析时,应事太多json.loads(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM