python-2.x

Making io.BufferedReader from sys.stdin in Python2

不羁岁月 提交于 2019-11-27 17:31:54
问题 How can I make a BufferedReader object from a standard file object, like sys.stdin or what you get from 'open'? (Background: I need a peek() method, which the standard file objects fail at having. Any suggestions to solve this issue are also welcome.) I'd have sort of expected this to work, but it doesn't: >>> import sys >>> import io >>> io.BufferedReader(sys.stdin) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'file' object has no attribute 'readable

Python: Using .format() on a Unicode-escaped string

試著忘記壹切 提交于 2019-11-27 17:13:40
I am using Python 2.6.5. My code requires the use of the "more than or equal to" sign. Here it goes: >>> s = u'\u2265' >>> print s >>> ≥ >>> print "{0}".format(s) Traceback (most recent call last): File "<input>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode character u'\u2265' in position 0: ordinal not in range(128)` Why do I get this error? Is there a right way to do this? I need to use the .format() function. Just make the second string also a unicode string >>> s = u'\u2265' >>> print s ≥ >>> print "{0}".format(s) Traceback (most recent call last): File "<stdin>",

How to check if variable is string with python 2 and 3 compatibility

∥☆過路亽.° 提交于 2019-11-27 17:13:39
I'm aware that I can use: isinstance(x, str) in python-3.x but I need to check if something is a string in python-2.x as well. Will isinstance(x, str) work as expected in python-2.x? Or will I need to check the version and use isinstance(x, basestr) ? Specifically, in python-2.x: >>>isinstance(u"test", str) False and python-3.x does not have u"foo" If you're writing 2.x-and-3.x-compatible code, you'll probably want to use six : from six import string_types isinstance(s, string_types) The most terse approach I've found without relying on packages like six, is: try: basestring except NameError:

An equivalent to string.ascii_letters for unicode strings in python 2.x?

风流意气都作罢 提交于 2019-11-27 16:09:50
问题 In the "string" module of the standard library, string.ascii_letters ## Same as string.ascii_lowercase + string.ascii_uppercase is 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' Is there a similar constant which would include everything that is considered a letter in unicode? 回答1: You can construct your own constant of Unicode upper and lower case letters with: import unicodedata as ud all_unicode = ''.join(unichr(i) for i in xrange(65536)) unicode_letters = ''.join(c for c in all

Pretty print JSON dumps

妖精的绣舞 提交于 2019-11-27 15:47:36
问题 I use this code to pretty print a dict into JSON: import json d = {'a': 'blah', 'b': 'foo', 'c': [1,2,3]} print json.dumps(d, indent = 2, separators=(',', ': ')) Output: { "a": "blah", "c": [ 1, 2, 3 ], "b": "foo" } This is a little bit too much (newline for each list element!). Which syntax should I use to have this: { "a": "blah", "c": [1, 2, 3], "b": "foo" } instead? 回答1: Write your own JSON serializer: import numpy INDENT = 3 SPACE = " " NEWLINE = "\n" def to_json(o, level=0): ret = "" if

Python long filename support broken in Windows

半城伤御伤魂 提交于 2019-11-27 15:40:33
I write Python script to copy files; unfortunately it keeps failing because filename is too long(>256). Is there anyway to deal with that problem? I'm using Python 2.5.4 and Windows XP. Cheers, Use paths beginning with the string \\?\ . In order to use the \\?\ prefix (as already proposed), you also need to make sure you use Unicode strings as filenames, not regular (byte) strings. Have you tried the workarounds suggested in this old thread, exp. the "magic prefix" trick? I don't know if the underyling issue (that we're not using the right one out of the many available Windows APIs for files)

Why does 4 < '3' return True in Python 2?

爷,独闯天下 提交于 2019-11-27 15:27:04
Why does 4 < '3' return True in Python 2? Is it because when I place single quotes around a number Python sees it as a string and strings are bigger than numbers? Yes, any number will be less than any string (including the empty string) in Python 2. In Python 3, you can't make arbitrary comparisons. You'll get a TypeError . From the link in eryksun's comment : if (PyNumber_Check(v)) vname = ""; else vname = v->ob_type->tp_name; if (PyNumber_Check(w)) wname = ""; else wname = w->ob_type->tp_name; c = strcmp(vname, wname); So at least in recent versions of CPython 2.x, type names are compared,

What is the advantage of the new print function in Python 3.x over the Python 2 print statement?

随声附和 提交于 2019-11-27 14:15:27
I've heard several times that print being a function (3.x) is better than it being a statement (2.x). But why? I was a fan of it being a statement mainly because it allowed me to type two less characters (ie, the parentheses). I'd be interested to see some situations where the print statement just doesn't cut it, and a function is superior. Lennart Regebro Everything from Jochen's answer and Sven's answer , plus: You can use print() it in places where you can't use print , such as: [print(x) for x in range(10)] Jochen Ritzel Rationale The print statement has long appeared on lists of dubious

Fast string array - Cython

只愿长相守 提交于 2019-11-27 13:20:07
Having following hypothetical code: cdef extern from "string.h": int strcmp(char* str1, char* str2) def foo(list_str1, list_str2): cdef unsigned int i, j c_arr1 = ?? c_arr2 = ?? for i in xrange(len(list_str1)): for j in xrange(len(list_str2)): if not strcmp(c_arr1[i], c_arr2[j]): do some funny stuff is there some way how to convert the lists to c arrays? I have read and tried Cython - converting list of strings to char ** but that only throws errors. Try following code. to_cstring_array function in the following code is what you want. from libc.stdlib cimport malloc, free from libc.string

How to accomplish relative import in python

强颜欢笑 提交于 2019-11-27 13:10:47
stuff/ __init__.py mylib.py Foo/ __init__.py main.py foo/ __init__.py script.py script.py wants to import mylib.py This is just an example, but really I just want to do a relative import of a module in a parent directory. I've tried various things and get this error... Attempted relative import beyond toplevel package I read somewhere that the script from where the program starts shouldn't in the package, and I tried modifying the structure for that like so... stuff/ mylib.py foo.py // equivalent of main.py in above foo/ __init__.py script.py but got same error. How can I accomplish this? Is