【问题标题】:How to remove u is indicating that the strings are unicode如何删除 u 表示字符串是 unicode
【发布时间】:2013-07-08 01:53:45
【问题描述】:

我想用"'" 替换字符"u '",我在谷歌上找到了解决方案。

我有这个版本的python:

user@ubuntu:/media/DATA/prototi/prototypefin4$ python --version
Python 2.7.4

我尝试替换和info

strg = jsondict.replace("u'", "'")
        print "\n\n\n\n\n\n\n\n\n\n\n"
        print strg 
        print "\n\n\n\n\n\n\n"

而我的服务器在cherrypy中我有这个错误:

    Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/cherrypy/_cprequest.py", line 656, in respond
    response.body = self.handler()
  File "/usr/lib/python2.7/dist-packages/cherrypy/lib/encoding.py", line 188, in __call__
    self.body = self.oldhandler(*args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/cherrypy/_cpdispatch.py", line 34, in __call__
    return self.callable(*self.args, **self.kwargs)
  File "web_editormy.py", line 585, in save_demo
    strg = jsondict.replace("u'", "'")
AttributeError: 'dict' object has no attribute 'replace'

这是变量 jsondict:

{u'demo_title': u'Demo title', u'proc1_script': u'script.sh parameters', u'inputp3_id': u'pepepe', u'outputp2_value': u'boh', u'demo_input_description': u'hola mundo', u'titleimg3': u'Gardens', u'outputp4_visible': u'on'}

我想删除u的这种恐怖

由于我将此变量的内容jsondict 打印到文件中。 所以没有这个比较好u

为什么不使用替换功能?

想念python的库吗?

这些是我加载的

   # -*- coding: utf-8 -*-

import urllib


import hashlib
from datetime import datetime
from random import random

#################################################

import json
from StringIO import StringIO

import re

#################################################

from mako.template import Template
from mako.lookup import TemplateLookup
from mako.exceptions import RichTraceback

#################################################

import os, shutil
from lib import index_dict, http_redirect_303

import zipfile
import sys

######################3

import cherrypy
from cherrypy.lib.static import serve_file

from config import file_dict

我哪里错了?

【问题讨论】:

  • jsondict 是字典而不是字符串
  • ok.. 并且有替换字符的可能性,因为我不喜欢字符u '
  • u 不是字符串中的字符,u 表示字符串是 unicode。你不“喜欢”它是什么意思?
  • @DavidRobinson 我认为他的意思是多余的空格
  • 我不知道这个迹象。由于我将此变量的内容jsondict 打印到文件中。所以没有这个u比较好。

标签: python python-2.7 cherrypy


【解决方案1】:

jsondict 是你存储数据的字典?我搜索了dict的所有属性,没有一个名为'replace'的arrtribute。所以,您可能需要从dict中读取数据作为字符串,然后使用字符串的方法'replace'将“u”替换为"'"。

对您尝试做的事情有些误解。实际上,“u'”不是dict值的一部分,这意味着str是unicode。如果您想删除“u'”,可以这样做像这样:dict['key'] = dict['key'].encode('utf-8'),你需要遍历整个jsondict。

【讨论】:

  • ueeeee 我认为可以禁用 u 的指示?替换时的作品是平等的..
【解决方案2】:

u'' 只是一个 unicode 文字,如果您看到这是因为您获得的是 python 值的表示,而不是值。

要生成 JSON 表示,只需使用 python 字典:

json_string = json.dumps(jsondict)
with open('output.json', 'w') as outfile:
    outfile.write(json_string)

或更好:

with open('output.json', 'w') as outfile:
     json.dump(jsondict, outfile)

【讨论】:

    猜你喜欢
    • 2017-02-20
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    • 2017-07-09
    相关资源
    最近更新 更多