python-2.x

Python: repr vs backquote

依然范特西╮ 提交于 2019-12-10 12:39:52
问题 In python, is there a difference between repr and the backquote ` (left of 1)? For demonstration: class A(object): def __repr__(self): return 'repr A' def __str__(self): return 'str A' >>> a = A() >>> repr(a) #'repr A' >>> `a` #'repr A' >>> str(a) #'str A' Do the backquotes just call repr ? Is it simply for convenience? Is there any significant speed difference? Thanks! 回答1: They're an alias for repr . They have the exact same effect. However, they're deprecated and have been removed in

Python, replace long dash with short dash?

断了今生、忘了曾经 提交于 2019-12-10 12:38:55
问题 I want to replace a long dash ( – ) with a short dash ( - ). My code: if " – " in string: string = string.replace(" – ", " - ") results in the following error: SyntaxError: Non-ASCII character '\xe2' in file ./script.py on line 76, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details How can I fix this? 回答1: Long dash is not an ASCII character. Declare encoding of your script, like this (somewhere on top) : #-*- coding: utf-8 -*- There are also other encodings

python3 datetime.timestamp in python2?

依然范特西╮ 提交于 2019-12-10 12:32:00
问题 I have a piece of python 3 code, that calls a function at 22:00. # Imports from datetime import datetime, date, time, timedelta import sched import time as mod_time # Find the next datetime corresponding to 22:00 first_run = datetime.combine(date.today(), time(22,0)) first_run = first_run if first_run > datetime.now() else first_run + timedelta(1) # Dumb test function def my_function(): print('my_function') # Run the function at 22:00 scheduler = sched.scheduler(mod_time.time, mod_time.sleep)

Python strings and str() method encoding and decoding

最后都变了- 提交于 2019-12-10 10:59:05
问题 I see that the Python manual mentions .encode() and .decode() string methods. Playing around on the Python CLI I see that I can create unicode strings u'hello' with a different datatype than a 'regular' string 'hello' and can convert / cast with str() . But the real problems start when using characters above ASCII 127 u'שלום' and I am having a hard time determining empirically exactly what is happening. Stack Overflow is overflowing with examples of confusion regarding Python's unicode and

Catch Broken Pipe in Python 2 AND Python 3

亡梦爱人 提交于 2019-12-10 03:03:45
问题 I try to write some code to catch a Broken Pipe Error. The code should run in Python 2.x and Python 3.x. In Python 2.x a broken pipe is represented by a socket.error socket.error: [Errno 32] Broken pipe This was changed in Python 3.x - a broken pipe now is a BrokenPipeError BrokenPipeError: [Errno 32] Broken pipe Also the syntax of exception handling has changed a bit (see https://stackoverflow.com/a/34463112/263589) so what I need to do would be something like: try: do_something() except

Why does this key class for sorting heterogeneous sequences behave oddly?

廉价感情. 提交于 2019-12-10 02:56:22
问题 Python 3.x's sorted() function cannot be relied on to sort heterogeneous sequences, because most pairs of distinct types are unorderable (numeric types like int , float , decimal.Decimal etc. being an exception): Python 3.4.2 (default, Oct 8 2014, 08:07:42) [GCC 4.8.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> sorted(["one", 2.3, "four", -5]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unorderable types: float() <

Returning the first N characters of a unicode string

回眸只為那壹抹淺笑 提交于 2019-12-10 02:22:42
问题 I have a string in unicode and I need to return the first N characters. I am doing this: result = unistring[:5] but of course the length of unicode strings != length of characters. Any ideas? The only solution is using re? Edit: More info unistring = "Μεταλλικα" #Metallica written in Greek letters result = unistring[:1] returns-> ? I think that unicode strings are two bytes (char), that's why this thing happens. If I do: result = unistring[:2] I get M which is correct, So, should I always

how to print directly to a text file in both python 2.x and 3.x?

萝らか妹 提交于 2019-12-10 01:04:31
问题 Instead of using write() , what are the other way to write to a text file in Python 2 and 3? file = open('filename.txt', 'w') file.write('some text') 回答1: You can use the print_function future import to get the print() behaviour from python3 in python2: from __future__ import print_function with open('filename', 'w') as f: print('some text', file=f) If you do not want that function to append a linebreak at the end, add the end='' keyword argument to the print() call. However, consider using f

How do I tell dict() in Python 2 to use unicode instead of byte string?

喜你入骨 提交于 2019-12-09 18:20:42
问题 Here is an example: d = dict(a = 2) print d {'a': 2} How can I tell dict() constructor to use Unicode instead without writing the string literal expliclity like u'a' ? I am loading a dictionary from a json module which defaults to use unicode. I want to make use of unicode from now on. 回答1: To get a dict with Unicode keys, use Unicode strings when constructing the dict: >>> d = {u'a': 2} >>> d {u'a': 2} Dicts created from keyword arguments always have string keys. If you want those to be

Modify URL components in Python 2

走远了吗. 提交于 2019-12-09 16:31:55
问题 Is there a cleaner way to modify some parts of a URL in Python 2? For example http://foo/bar -> http://foo/yah At present, I'm doing this: import urlparse url = 'http://foo/bar' # Modify path component of URL from 'bar' to 'yah' # Use nasty convert-to-list hack due to urlparse.ParseResult being immutable parts = list(urlparse.urlparse(url)) parts[2] = 'yah' url = urlparse.urlunparse(parts) Is there a cleaner solution? 回答1: Unfortunately, the documentation is out of date; the results produced