python-2.x

how to decode an ascii string with backslash x \\x codes

余生颓废 提交于 2019-12-04 03:12:38
I am trying to decode from a Brazilian Portogese text: 'Demais Subfun\xc3\xa7\xc3\xb5es 12' It should be 'Demais Subfunções 12' >> a.decode('unicode_escape') >> a.encode('unicode_escape') >> a.decode('ascii') >> a.encode('ascii') all give: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 13: ordinal not in range(128) on the other hand this gives: >> print a.encode('utf-8') Demais Subfun├â┬º├â┬Áes 12 >> print a Demais Subfunções 12 Martijn Pieters You have binary data that is not ASCII encoded. The \xhh codepoints indicate your data is encoded with a different codec, and

What does python print() function actually do?

拜拜、爱过 提交于 2019-12-04 03:02:59
I was looking at this question and started wondering what does the print actually do. I have never found out how to use string.decode() and string.encode() to get an unicode string "out" in the python interactive shell in the same format as the print does. No matter what I do, I get either UnicodeEncodeError or the escaped string with "\x##" notation... This is python 2.x, but I'm already trying to mend my ways and actually call print() :) Example: >>> import sys >>> a = '\xAA\xBB\xCC' >>> print(a) ª»Ì >>> a.encode(sys.stdout.encoding) Traceback (most recent call last): File "<stdin>", line 1,

Why are 008 and 009 invalid keys for Python dicts?

亡梦爱人 提交于 2019-12-04 02:52:50
问题 Why is it that I can't have 008 or 009 be keys for a Python dict, but 001-007 are fine? Example: some_dict = { 001: "spam", 002: "eggs", 003: "foo", 004: "bar", 008: "anything", # Throws a SyntaxError 009: "nothing" # Throws a SyntaxError } Update : Problem solved. I wasn't aware that starting a literal with a zero made it octal. That seems really odd. Why zero? 回答1: In python and some other languages, if you start a number with a 0, the number is interpreted as being in octal (base 8), where

Python: Convert tuple to comma separated String

依然范特西╮ 提交于 2019-12-04 01:38:30
问题 import MySQLdb db = MySQLdb.connect("localhost","root","password","database") cursor = db.cursor() cursor.execute("SELECT id FROM some_table") u_data = cursor.fetchall() >>> print u_data ((1320088L,),) What I found on internet got me till here: string = ((1320088L,),) string = ','.join(map(str, string)) >>> print string (1320088L,) what I expect output to look like: #Single element expected result 1320088L #comma separated list if more than 2 elements, below is an example 1320088L,1320089L

unicode_literals and type()

前提是你 提交于 2019-12-04 00:50:54
I'm having problems supporting python2 and python3 on a type() call. This demonstrates the problem: from __future__ import unicode_literals name='FooClass' type(name, (dict,), {}) No problem on python3, but on python2: Traceback (most recent call last): File "test.py", line 6, in <module> type(name, (dict,), {}) TypeError: type() argument 1 must be string, not unicode This is related to Any gotchas using unicode_literals in Python 2.6? . In that question, someone recommends typecasting to a bytestring, so naively I thought about using six.b() : A “fake” bytes literal. data should always be a

python closure with assigning outer variable inside inner function

旧街凉风 提交于 2019-12-04 00:11:15
问题 I've got this piece of code: #!/usr/bin/env python def get_match(): cache=[] def match(v): if cache: return cache cache=[v] return cache return match m = get_match() m(1) if I run it, it says: UnboundLocalError: local variable 'cache' referenced before assignment but if I do this: #!/usr/bin/env python def get(): y = 1 def m(v): return y + v return m a=get() a(1) it runs. Is there something with list? or my code organizing is wrong? 回答1: The problem is that the variable cache is not in the

Difference between io.open vs open in python

守給你的承諾、 提交于 2019-12-03 23:45:02
In the past, there's codecs which got replaced by io . Although it seems like it's more advisable to use io.open , most introductory python classes still teaches open . There's a question with Difference between open and codecs.open in Python but is open a mere duck-type of io.open ? If not, why is it better to use io.open ? And why is it easier to teach with open ? In this post ( http://code.activestate.com/lists/python-list/681909/ ), Steven DAprano says that the built in open is using the io.open in the backend. So should we all refactored our code to use open instead of io.open ? Other

Why can't I use `import *` in a function?

雨燕双飞 提交于 2019-12-03 23:21:54
This works as expected def outer_func(): from time import * print time() outer_func() I can define nested functions in the context fine and call them from other nested functions: def outer_func(): def time(): return '123456' def inner_func(): print time() inner_func() outer_func() I can even import individual functions: def outer_func(): from time import time def inner_func(): print time() inner_func() outer_func() This, however, throws SyntaxError: import * is not allowed in function 'outer_func' because it contains a nested function with free variables : def outer_func(): from time import *

2d dictionary with many keys that will return the same value

风流意气都作罢 提交于 2019-12-03 22:14:06
I want to make a 2d dictionary with multiple keys per value. I do not want to make a tuple a key. But rather make many keys that will return the same value. I know how to make a 2d dictionary using defaultdict: from collections import defaultdict a_dict = defaultdict(dict) a_dict['canned_food']['spam'] = 'delicious' And I can make a tuple a key using a_dict['food','canned_food']['spam'] = 'delicious' But this does not allow me to do something like print a_dict['canned_food]['spam'] Because 'canned_food' is not a key the tuple ['food','canned_food'] is the key. I have learned that I can simply

Reading russian language data from csv

穿精又带淫゛_ 提交于 2019-12-03 20:50:18
I have some data in CSV file that are in Russian: 2-комнатная квартира РДТ', мкр Тастак-3, Аносова — Толе би;Алматы 2-комнатная квартира БГР', мкр Таугуль, Дулати (Навои) — Токтабаева;Алматы 2-комнатная квартира ЦФМ', мкр Тастак-2, Тлендиева — Райымбека;Алматы Delimiter is ; symbol. I want to read data and put it into array. I tried to read this data using this code: def loadCsv(filename): lines = csv.reader(open(filename, "rb"),delimiter=";" ) dataset = list(lines) for i in range(len(dataset)): dataset[i] = [str(x) for x in dataset[i]] return dataset Then I read and print result: mydata =