【问题标题】:converting a string of unicode strings to normal string without single quotes in python在python中将一串unicode字符串转换为没有单引号的普通字符串
【发布时间】:2014-11-29 20:34:55
【问题描述】:

这是正在读取的代码中的 json 文件(file2):

[
    {
        "Id": "cl",
        "description": "Creates",
        "statements": [
            "Sentence1",
            "Sentence2",
            "Sentence3"
        ],
        "parameters": [
            {
                "name": "Id",
                "required": true,
                "description": "Start date for rundate"
            }
        ]
    }
]

这是python代码:

file2=sys.argv[2];
loc_file_2=str(sys.argv[2])  ;
open_json_2=open(loc_file_2);
data_2=json.load(open_json_2);

Query_statements_list=data_2[0].get('statements');

json_input_string="";

json_input_string=str(Query_statements_list);

print json_input_string.encode('utf-8');

打印输出:

[u'Sentence1', u'Sentence2', u'Sentence3']

我希望将输出从字符串的 unicode 字符串转换为普通字符串,并且没有那些单引号和逗号,这样我就得到了一个字符串 str

例如:

str= Sentence1Sentence2Sentence3

【问题讨论】:

  • 为什么要丢弃信息?

标签: python json unicode-string


【解决方案1】:

当您在一个列表上使用str 时,您只会得到该列表在 Python 语法中的表示。

如果你想要别的东西,你应该使用一些字符串操作。例如,您可以使用str.join 来生成您想要的输出:

json_input_string = ''.join(Query_statements_list)

使json_input_string 等于Sentence1Sentence2Sentence3。您可以更改用于连接的字符串以获得不同的结果。例如,

json_input_string = ':'.join(Query_statements_list)

会产生Sentence1:Sentence2:Sentence3

【讨论】:

  • 嗨 nneonneo,如果我得到以下输出 "Sentence1",FLAG "Sentence2",FLAG "Sentence3"FLAG 都在 FLAG 之后的新行上,那么我如何获得 Sentence1FLAGSentence2FLAGSentence3FLAG ?
猜你喜欢
  • 1970-01-01
  • 2016-06-18
  • 1970-01-01
  • 2012-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多