python新手必然碰到的问题?如何让u前缀接受变量?

pyruby 发布于 2013/11/04 10:02
阅读 7K+
收藏 0

【开源中国 APP 全新上线】“动弹” 回归、集成大模型对话、畅读技术报告”

这个应该是每个python新手都会遇到的问题把

一般的代码

string = u"\u5982\u679c"

print string

现在如果u后面的是未知的变量,如何让它也能达到上面的效果呢?

我试了u(变量)不行。。

加载中
0
fc_lamp
fc_lamp

你指的是什么?

如果你说的是:json像这种

>>> import json
>>> js = '{"one":"\u5982\u679c"}'
>>> type(js)
<type 'str'>
>>> js = json.JSONDecoder().decode(js)
>>> js
{u'one': u'\u5982\u679c'}
>>> type(js)
<type 'dict'>
>>> print js['one']
如果
>>> type(js['one'])
<type 'unicode'>

还是纯字符串:

>>> s = '\u5982\u679c'
>>> s = "u'%s'"%(s)
>>> s
"u'\\u5982\\u679c'"
>>> type(s)
<type 'str'>
>>> s = eval(s)
>>> type(s)
<type 'unicode'>
>>> print s
如果


参:http://fc-lamp.blog.163.com/blog/static/1745666872012121240969/






1
pyruby
pyruby

引用来自“Narky”的答案

print u"%s" % (var1,)

这样子

print eval("u'%s'" %(s))
 你这样的话打印字符串了

B
Brilliantree
非常感谢!解决大问题了
0
伊藤熊吉
伊藤熊吉

unicode() 函数?

0
pyruby
pyruby

引用来自“伊藤熊吉”的答案

unicode() 函数?

不行的
0
Narky
Narky
print u"%s" % (var1,)
0
ToughGuy
ToughGuy
该评论暂时无法显示,详情咨询 QQ 群:点此入群
0
pyruby
pyruby

引用来自“fc_lamp”的答案

你指的是什么?

如果你说的是:json像这种

>>> import json
>>> js = '{"one":"\u5982\u679c"}'
>>> type(js)
<type 'str'>
>>> js = json.JSONDecoder().decode(js)
>>> js
{u'one': u'\u5982\u679c'}
>>> type(js)
<type 'dict'>
>>> print js['one']
如果
>>> type(js['one'])
<type 'unicode'>

还是纯字符串:

>>> s = '\u5982\u679c'
>>> s = "u'%s'"%(s)
>>> s
"u'\\u5982\\u679c'"
>>> type(s)
<type 'str'>
>>> s = eval(s)
>>> type(s)
<type 'unicode'>
>>> print s
如果


参:http://fc-lamp.blog.163.com/blog/static/1745666872012121240969/






OK。
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部