Python-字符串值前面的“ u”符号是什么意思?
是的,总之,我想知道为什么我在我的键和值前面看到au。
我正在渲染表格。该表格具有用于特定标签的复选框和用于IP地址的一个文本字段。我正在创建一个字典,其键为标签,这些键在list_key中进行了硬编码,并且字典的值取自表单输入(list_value)。字典已创建,但对于某些值,其前面带有u。这是字典的示例输出:
{u'1': {'broadcast': u'on', 'arp': '', 'webserver': '', 'ipaddr': u'', 'dns': ''}}
有人可以解释我在做什么错。当我在pyscripter中模拟类似方法时,我没有收到错误消息。欢迎提出任何改进代码的建议。谢谢
`#!/usr/bin/env python
import webapp2
import itertools
import cgi
form =”“”
<label> Allow Broadcast
<input type="checkbox" name="broadcast">
</label>
<br><br>
<label> Allow ARP
<input type="checkbox" name="arp">
</label><br><br>
<label> Allow Web traffic from external address to internal webserver
<input type="checkbox" name="webserver">
</label><br><br>
<label> Allow DNS
<input type="checkbox" name="dns">
</label><br><br>
<label> Block particular Internet Protocol address
<input type="text" name="ipaddr">
</label><br><br>
<input type="submit">
</form>
”“”
dictionarymain={}
class MainHandler(webapp2.RequestHandler):
def get(self):
self.response.out.write(form)
def post(self):
# get the parameters from the form
profile = self.request.get('profiles')
broadcast = self.request.get('broadcast')
arp = self.request.get('arp')
webserver = self.request.get('webserver')
dns =self.request.get('dns')
ipaddr = self.request.get('ipaddr')
# Create a dictionary for the above parameters
list_value =[ broadcast , arp , webserver , dns, ipaddr ]
list_key =['broadcast' , 'arp' , 'webserver' , 'dns' , 'ipaddr' ]
#self.response.headers['Content-Type'] ='text/plain'
#self.response.out.write(profile)
# map two list to a dictionary using itertools
adict = dict(zip(list_key,list_value))
self.response.headers['Content-Type'] ='text/plain'
self.response.out.write(adict)
if profile not in dictionarymain:
dictionarymain[profile]= {}
dictionarymain[profile]= adict
#self.response.headers['Content-Type'] ='text/plain'
#self.response.out.write(dictionarymain)
def escape_html(s):
return cgi.escape(s, quote =True)
app = webapp2.WSGIApplication([(‘/’, MainHandler)],
debug=True)`
-
字符串值前面的“ u”表示该字符串已表示为unicode。字符串前面的字母称为“字符串编码声明”。Unicode是一种表示比普通ascii可以管理的字符更多的字符的方法。
你可以通过多种方式将字符串转换为unicode:
>>> u'foo' u'foo' >>> unicode('foo') u'foo'
但是真正的原因是要代表这样的东西(在这里翻译):
>>> val = u'Ознакомьтесь с документацией' >>> val u'\u041e\u0437\u043d\u0430\u043a\u043e\u043c\u044c\u0442\u0435\u0441\u044c \u0441 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0435\u0439' >>> print val Ознакомьтесь с документацией
在大多数情况下,在此代码中将它们与ascii字符串区别对待时,应该不会有任何错误。
你还会看到其他符号,例如“ raw”符号,用于告诉字符串不要解释任何特殊字符。在python中执行正则表达式时,这非常有用。
>>> 'foo\"' 'foo"' >>> r'foo\"' 'foo\\"' ASCII和Unicode字符串在逻辑上可以等效: >>> bird1 = unicode('unladen swallow') >>> bird2 = 'unladen swallow' >>> bird1 == bird2 True