title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Substring Comparison in python
3,524,611
4
2010-08-19T17:44:39Z
3,524,630
13
2010-08-19T17:46:50Z
[ "python" ]
If i have List PhoneDirectory Eg: ``` ['John:009878788677' , 'Jefrey:67654654645' , 'Maria:8787677766'] ``` Which is the function that can be use to compare the Presence of Substring (Eg: Joh) in each entry in the List . I have tried using ``` if(PhoneDirectory.find(Joh) != -1) ``` but it doesnt work kindly Help....
If you want to check each entry separately: ``` for entry in PhoneDirectory: if 'John' in entry: ... ``` If you just want to know if *any* entry satisfies the condition and don't care which one: ``` if any('John' in entry for entry in PhoneDirectory): ... ``` Note that `any` will do no "wasted" work -- it w...
Python sum, why not strings?
3,525,359
41
2010-08-19T19:13:30Z
3,525,380
35
2010-08-19T19:15:55Z
[ "python", "design", "types", "sum", "built-in" ]
Python has a built in function `sum`, which is effectively equivalent to: ``` def sum2(iterable, start=0): return start + reduce(operator.add, iterable) ``` for all types of parameters except strings. It works for numbers and lists, for example: ``` sum([1,2,3], 0) = sum2([1,2,3],0) = 6 #Note: 0 is the defau...
Python tries to discourage you from "summing" strings. You're supposed to join them: ``` "".join(list_of_strings) ``` It's a lot faster, and uses much less memory. A quick benchmark: ``` $ python -m timeit -s 'import operator; strings = ["a"]*10000' 'r = reduce(operator.add, strings)' 100 loops, best of 3: 8.46 mse...
Python sum, why not strings?
3,525,359
41
2010-08-19T19:13:30Z
3,525,383
12
2010-08-19T19:16:24Z
[ "python", "design", "types", "sum", "built-in" ]
Python has a built in function `sum`, which is effectively equivalent to: ``` def sum2(iterable, start=0): return start + reduce(operator.add, iterable) ``` for all types of parameters except strings. It works for numbers and lists, for example: ``` sum([1,2,3], 0) = sum2([1,2,3],0) = 6 #Note: 0 is the defau...
From [the docs](http://docs.python.org/library/functions.html#sum): > The preferred, fast way to concatenate a > sequence of strings is by calling > ''.join(sequence). By making `sum` refuse to operate on strings, Python has encouraged you to use the correct method.
Python sum, why not strings?
3,525,359
41
2010-08-19T19:13:30Z
3,525,725
17
2010-08-19T20:01:06Z
[ "python", "design", "types", "sum", "built-in" ]
Python has a built in function `sum`, which is effectively equivalent to: ``` def sum2(iterable, start=0): return start + reduce(operator.add, iterable) ``` for all types of parameters except strings. It works for numbers and lists, for example: ``` sum([1,2,3], 0) = sum2([1,2,3],0) = 6 #Note: 0 is the defau...
You can in fact use `sum(..)` to concatenate strings, if you use the appropriate starting object! Of course, if you go this far you have already understood enough to use `"".join(..)` anyway.. ``` >>> class ZeroObject(object): ... def __add__(self, other): ... return other ... >>> sum(["hi", "there"], ZeroObject())...
Python sum, why not strings?
3,525,359
41
2010-08-19T19:13:30Z
3,528,260
7
2010-08-20T04:46:26Z
[ "python", "design", "types", "sum", "built-in" ]
Python has a built in function `sum`, which is effectively equivalent to: ``` def sum2(iterable, start=0): return start + reduce(operator.add, iterable) ``` for all types of parameters except strings. It works for numbers and lists, for example: ``` sum([1,2,3], 0) = sum2([1,2,3],0) = 6 #Note: 0 is the defau...
Short answer: Efficiency. Long answer: The `sum` function has to create an object for each partial sum. Assume that the amount of time required to create an object is directly proportional to the size of its data. Let N denote the number of elements in the sequence to sum. `double`s are always the same size, which m...
Python sum, why not strings?
3,525,359
41
2010-08-19T19:13:30Z
3,528,357
11
2010-08-20T05:15:12Z
[ "python", "design", "types", "sum", "built-in" ]
Python has a built in function `sum`, which is effectively equivalent to: ``` def sum2(iterable, start=0): return start + reduce(operator.add, iterable) ``` for all types of parameters except strings. It works for numbers and lists, for example: ``` sum([1,2,3], 0) = sum2([1,2,3],0) = 6 #Note: 0 is the defau...
Here's the source: <http://svn.python.org/view/python/trunk/Python/bltinmodule.c?revision=81029&view=markup> In the builtin\_sum function we have this bit of code: ``` /* reject string values for 'start' parameter */ if (PyObject_TypeCheck(result, &PyBaseString_Type)) { PyErr_SetString(PyExc_...
Python, creating a new variable from a dictionary? not as straightforward as it seems?
3,525,453
3
2010-08-19T19:24:30Z
3,525,516
7
2010-08-19T19:31:37Z
[ "python", "dictionary" ]
I'm trying to create a new variable that will consist of an existing dictionary so that I can change things in this new dictionary without it affecting the old one. When I try this below, which I think would be the obvious way to do this, it still seems to edit my original dictionary when I make edits to the new one.. ...
You're creating a reference, instead of a copy. In order to make a complete copy and leave the original untouched, you need `copy.deepcopy()`. So: ``` from copy import deepcopy dictionary_new = deepcopy(dictionary_old) ``` Just using `a = dict(b)` or `a = b.copy()` will make a shallow copy and leave any lists in your...
Check if all values of iterable are zero
3,525,953
8
2010-08-19T20:32:29Z
3,525,971
8
2010-08-19T20:34:12Z
[ "python", "iterable" ]
Is there a good, succinct/built-in way to see if all the values in an iterable are zeros? Right now I am using `all()` with a little list comprehension, but (to me) it seems like there should be a more expressive method. I'd view this as somewhat equivalent to a `memcmp()` in C. ``` values = (0, 0, 0, 0, 0) # Test if ...
If you know that the iterable will contain only integers then you can just do this: ``` if not any(values): # etc... ```
Check if all values of iterable are zero
3,525,953
8
2010-08-19T20:32:29Z
3,526,286
30
2010-08-19T21:11:58Z
[ "python", "iterable" ]
Is there a good, succinct/built-in way to see if all the values in an iterable are zeros? Right now I am using `all()` with a little list comprehension, but (to me) it seems like there should be a more expressive method. I'd view this as somewhat equivalent to a `memcmp()` in C. ``` values = (0, 0, 0, 0, 0) # Test if ...
Use generators rather than lists in cases like that: ``` all(v == 0 for v in values) ``` **Edit:** `all` is standard Python built-in. If you want to be efficient Python programmer you should know probably more than half of them (http://docs.python.org/library/functions.html). Arguing that `alltrue` is better name th...
Pythonic way to compare two lists and print the unmatched items?
3,526,196
2
2010-08-19T20:58:58Z
3,526,264
8
2010-08-19T21:08:59Z
[ "python", "list" ]
I have two Python lists of dictionaries, `entries9` and `entries10`. I want to compare the items and write joint items to a new list called `joint_items`. I also want to save the unmatched items to two new lists, `unmatched_items_9` and `unmatched_items_10`. This is my code. Getting the `joint_items` and `unmatched_it...
The equivalent of what you're currently doing, but the other way around, is: ``` unmatched_items_10 = [d for d in entries10 if d not in entries9] ``` While more concise than your way of coding it, this has the same performance problem: it will take time proportional to the number of items in each list. If the lengths...
Problem with 2D interpolation in SciPy, non-rectangular grid
3,526,514
3
2010-08-19T21:44:30Z
3,576,551
10
2010-08-26T15:17:26Z
[ "python", "scipy", "interpolation" ]
I've been trying to use scipy.interpolate.bisplrep() and scipy.interpolate.interp2d() to find interpolants for data on my (218x135) 2D spherical-polar grid. To these I pass 2D arrays, X and Y, of the Cartesian positions of my grid nodes. I keep getting errors like the following (for linear interp. with interp2d): "War...
Added 27Aug: Kyle followed this up on a [scipy-user thread](http://groups.google.com/group/scipy-user/browse_thread/thread/78964a5afbd1f3a6#). 30Aug: @Kyle, it looks as though there's a mixup between Cartesion X,Y and polar Xnew,Ynew. See "polar" in the too-long notes below. ![alt text](http://i.stack.imgur.com/lXz17...
Move an email in GMail with Python and imaplib
3,527,933
18
2010-08-20T03:13:42Z
3,528,810
25
2010-08-20T07:04:45Z
[ "python", "gmail", "imap", "imaplib" ]
I want to be able to move an email in GMail from the inbox to another folder using Python. I am using imaplib and can't figure out how to do it.
There is no explicit move command for IMAP. You will have to execute a `COPY` followed by a `STORE` (with suitable flag to indicate deletion) and finally `expunge`. The example given below worked for moving messages from one label to the other. You'll probably want to add more error checking though. ``` import imaplib...
py2exe: Reduce size of the library archive
3,528,763
6
2010-08-20T06:54:26Z
3,528,818
7
2010-08-20T07:05:39Z
[ "python", "py2exe" ]
I just created my first py2exe executable and noticed that with the EXE, there is a ZIP file created with the size of around 1.4 MB. My question is, can I reduce the size of this or is it expected that the typical size of an EXE generated with py2exe will be ~ 4 MB (that means with all the files: python2.6dll, library...
Short answer to your size reduction question is yes. Long answer I am not going to provide here, but instead direct you to py2exe's [OptimizingSize](http://www.py2exe.org/index.cgi/OptimizingSize) wiki page. I hope this helps ;)
Find the largest image dimensions from list of images
3,529,552
3
2010-08-20T09:11:29Z
3,529,867
7
2010-08-20T10:01:47Z
[ "python" ]
I have a list (the paths) of images saved locally. How can I find the largest image from these? I'm not referring to the file size but the dimensions. All the images are in common web-compatible formats — JPG, GIF, PNG, etc. Thank you.
Assuming that the "size" of an image is its area : ``` from PIL import Image def get_img_size(path): width, height = Image.open(path).size return width*height largest = max(the_paths, key=get_img_size) ```
matplotlib matshow labels
3,529,666
7
2010-08-20T09:30:25Z
3,532,408
15
2010-08-20T15:33:21Z
[ "python", "django", "matplotlib", "labels" ]
I start using matplotlib a month ago, so I'm still learning. I'm trying to do a heatmap with matshow. My code is the following: ``` data = numpy.array(a).reshape(4, 4) cax = ax.matshow(data, interpolation='nearest', cmap=cm.get_cmap('PuBu'), norm=LogNorm()) cbar = fig.colorbar(cax) ax.set_xticklabels(alpha) a...
What's happening is that the xticks actually extend outside of the displayed figure when using matshow. (I'm not quite sure exactly why this is. I've almost never used matshow, though.) To demonstrate this, look at the output of `ax.get_xticks()`. In your case, it's `array([-1., 0., 1., 2., 3., 4.])`. Therefore, when ...
How to generate unique 64 bits integers from Python?
3,530,294
8
2010-08-20T11:09:09Z
3,530,326
20
2010-08-20T11:14:49Z
[ "python", "guid", "random", "uniqueidentifier", "uuid" ]
I need to generate unique 64 bits integers from Python. I've checked out the [UUID module](http://docs.python.org/library/uuid.html). But the UUID it generates are 128 bits integers. So that wouldn't work. Do you know of any way to generate 64 bits unique integers within Python? Thanks.
just mask the 128bit int ``` >>> import uuid >>> uuid.uuid4().int & (1<<64)-1 9518405196747027403L >>> uuid.uuid4().int & (1<<64)-1 12558137269921983654L ``` These are more or less random, so you have a tiny chance of a collision Perhaps the first 64 bits of uuid1 is safer to use ``` >>> uuid.uuid1().int>>64 939246...
How to generate unique 64 bits integers from Python?
3,530,294
8
2010-08-20T11:09:09Z
3,531,557
9
2010-08-20T13:59:53Z
[ "python", "guid", "random", "uniqueidentifier", "uuid" ]
I need to generate unique 64 bits integers from Python. I've checked out the [UUID module](http://docs.python.org/library/uuid.html). But the UUID it generates are 128 bits integers. So that wouldn't work. Do you know of any way to generate 64 bits unique integers within Python? Thanks.
> 64 bits unique What's wrong with counting? A simple counter will create unique values. This is the simplest and it's easy to be sure you won't repeat a value. Or, if counting isn't good enough, try this. ``` >>> import random >>> random.getrandbits(64) 5316191164430650570L ``` Depending on how you seed and use yo...
Unpack from hex to double in Python
3,531,723
4
2010-08-20T14:18:17Z
3,531,743
12
2010-08-20T14:20:20Z
[ "python", "double", "hex" ]
Python: Unpack from hex to double This is the value ``` value = ['\x7f', '\x15', '\xb7', '\xdb', '5', '\x03', '\xc0', '@'] ``` I tried ``` unpack('d', value) ``` but he needs a string for unpacking. It is a list now. But when I change it to a string, the length will change from 8 to 58. But a double needs a value ...
Use [`''.join`](http://docs.python.org/library/stdtypes.html#str.join) join to convert the list to a string: ``` >>> value = ['\x7f', '\x15', '\xb7', '\xdb', '5', '\x03', '\xc0', '@'] >>> ''.join(value) '\x7f\x15\xb7\xdb5\x03\xc0@' >>> from struct import unpack >>> unpack('d', ''.join(value)) (8198.4207676749193,) ```
Flipping bits in python
3,532,018
7
2010-08-20T14:50:48Z
3,532,096
11
2010-08-20T14:58:32Z
[ "python", "algorithm" ]
Given an integer n , i want to toggle all bits in the binary representation of that number in the range say lower to upper. To do this i do the following [bit\_string is a string containing 1's and 0's and is a binary representation of n] ``` for i in range(lower,upper+1): n ^= (1 << len(bit_string)-1-i) #Toggle th...
For the "flipping", you can make a single bitmap (with ones in all positions of interest) and a single exclusive-or: ``` n ^= ((1<<upper)-1)&~((1<<lower)-1) ``` For bit-counts, once you isolate (n & mask) for the same "mask" as the above RHS, slicing it into e.g. 8-bit slices and looking up the 8-bit counts in a look...
python: cannot concatenate 'str' and 'long' objects
3,532,873
7
2010-08-20T16:31:01Z
3,532,890
22
2010-08-20T16:33:19Z
[ "python" ]
I'm trying to set up a choice field in django, but I don't think this is a django issue. The choices field takes an iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field. Here's my code: ``` self.fields['question_' + question.id] = forms.ChoiceField( label=question.label, ...
Most likely it's highlighting the last line only because you split the statement over multiple lines. The fix for the *actual* problem will most likely be changing ``` self.fields['question_' + question.id] ``` to ``` self.fields['question_' + str(question.id)] ``` As you can quickly test in a Python interpreter, ...
Python Regular Expression Match All 5 Digit Numbers but None Larger
3,532,947
10
2010-08-20T16:40:26Z
3,532,978
8
2010-08-20T16:43:39Z
[ "python", "regex" ]
I'm attempting to string match 5-digit coupon codes spread throughout a HTML web page. For example, `53232`, `21032`, `40021` etc... I can handle the simpler case of any string of 5 digits with `[0-9]{5}`, though this also matches 6, 7, 8... n digit numbers. Can someone please suggest how I would modify this regular ex...
full string: `^[0-9]{5}$` within a string: `[^0-9][0-9]{5}[^0-9]`
Python Regular Expression Match All 5 Digit Numbers but None Larger
3,532,947
10
2010-08-20T16:40:26Z
3,533,002
23
2010-08-20T16:46:53Z
[ "python", "regex" ]
I'm attempting to string match 5-digit coupon codes spread throughout a HTML web page. For example, `53232`, `21032`, `40021` etc... I can handle the simpler case of any string of 5 digits with `[0-9]{5}`, though this also matches 6, 7, 8... n digit numbers. Can someone please suggest how I would modify this regular ex...
``` >>> import re >>> s="four digits 1234 five digits 56789 six digits 012345" >>> re.findall(r"\D(\d{5})\D", s) ['56789'] ``` if they can occur at the very beginning or the very end, it's easier to pad the string than mess with special cases ``` >>> re.findall(r"\D(\d{5})\D", " "+s+" ") ```
Python: How to download a zip file
3,532,979
6
2010-08-20T16:43:51Z
3,533,093
10
2010-08-20T16:57:50Z
[ "python" ]
I'm attempting to download a zip file using this code: ``` o = urllib2.build_opener( urllib2.HTTPCookieProcessor() ) #login p = urllib.urlencode( { usernameField: usernameVal, passField: passVal } ) f = o.open(authUrl, p ) data = f.read() print data f.close() #download file f = o.open(remoteFileUrl) localFile = ope...
`f.read()` doesn't necessarily read the whole file, but just a packet of it (which might be the whole file if it's small, but won't be for a large file). You need to loop over the packets like this: ``` while 1: packet = f.read() if not packet: break localFile.write(packet) f.close() ``` `f.read()` re...
random.randint for non integer number? [Python]
3,533,247
4
2010-08-20T17:15:59Z
3,533,268
12
2010-08-20T17:18:20Z
[ "python", "random" ]
How can I make a random number between something like 0.1 to 0.9 ? randint only work for integer numbers =/ Thank you
Use [random.uniform()](http://docs.python.org/library/random.html#random.uniform). For your example, `random.uniform(0.1, 0.9)`. It's equivalent to using random.random() to get a value between 0.0 and 1.0, then scaling and shifting the value appropriately: ``` def rand_float_range(start, end): return random.rando...
Python efficiency of and vs multiple ifs
3,533,338
8
2010-08-20T17:29:00Z
3,533,365
13
2010-08-20T17:33:25Z
[ "python", "performance", "conditional" ]
Is there an efficiency difference between using and in an if statement and using multiple if statements? In other words, is something like ``` if expr1 == expr2 and expr3==expr4: dostuff() ``` different from an efficiency standpoint then: ``` if expr1 == expr2: if expr3 == expr4: dostuff() ``` My very basic...
This isn't enough of a performance difference, if any, to affect your decision. IMO, the decision here should be made purely from a readability perspective. The first is generally more standard, I think, but there are situations when the second might be clearer. Choose the method that best gets your intent across.
Python Web Crawlers and "getting" html source code
3,533,528
12
2010-08-20T17:54:42Z
3,533,678
30
2010-08-20T18:15:33Z
[ "python", "get", "web-crawler" ]
So my brother wanted me to write a web crawler in Python (self-taught) and I know C++, Java, and a bit of html. I'm using version 2.7 and reading the python library, but I have a few problems 1. `httplib.HTTPConnection` and `request` concept to me is new and I don't understand if it downloads an html script like cookie...
~~Use Python 2.7, is has more 3rd party libs at the moment.~~ (**Edit:** see below). I recommend you using the stdlib module `urllib2`, it will allow you to comfortably get web resources. Example: ``` import urllib2 response = urllib2.urlopen("http://google.de") page_source = response.read() ``` For parsing the cod...
Performance differences between Python and C
3,533,759
12
2010-08-20T18:27:18Z
3,533,800
10
2010-08-20T18:33:00Z
[ "python", "c", "performance" ]
Working on different projects I have the choice of selecting different programming languages, as long as the task is done. I was wondering what the real difference is, in terms of performance, between writing a program in Python, versus doing it in C. The tasks to be done are pretty varied, e.g. sorting textfiles, di...
In general IO bound work will depend more on the algorithm then the language. In this case I would go with Python because it will have first class strings and lots of easy to use libraries for manipulating files, etc.
Performance differences between Python and C
3,533,759
12
2010-08-20T18:27:18Z
3,533,838
7
2010-08-20T18:39:09Z
[ "python", "c", "performance" ]
Working on different projects I have the choice of selecting different programming languages, as long as the task is done. I was wondering what the real difference is, in terms of performance, between writing a program in Python, versus doing it in C. The tasks to be done are pretty varied, e.g. sorting textfiles, di...
> Is there really a noticeable difference between sorting a textfile using the same algorithm in C versus Python, for example? Yes. The noticeable differences are these 1. There's much less Python code. 2. The Python code is much easier to read. 3. Python supports really nice unit testing, so the Python code tends t...
Performance differences between Python and C
3,533,759
12
2010-08-20T18:27:18Z
3,533,877
30
2010-08-20T18:44:44Z
[ "python", "c", "performance" ]
Working on different projects I have the choice of selecting different programming languages, as long as the task is done. I was wondering what the real difference is, in terms of performance, between writing a program in Python, versus doing it in C. The tasks to be done are pretty varied, e.g. sorting textfiles, di...
Use python until you have a performance problem. If you ever have one figure out what the problem is (often it isn't what you would have guessed up front). Then solve that specific performance problem which will likely be an algorithm or data structure change. In the rare case that your problem really needs C then you ...
Performance differences between Python and C
3,533,759
12
2010-08-20T18:27:18Z
3,534,125
9
2010-08-20T19:17:27Z
[ "python", "c", "performance" ]
Working on different projects I have the choice of selecting different programming languages, as long as the task is done. I was wondering what the real difference is, in terms of performance, between writing a program in Python, versus doing it in C. The tasks to be done are pretty varied, e.g. sorting textfiles, di...
C will absolutely crush Python in almost any performance category, but C is far more difficult to write and maintain and high performance isn't always worth the trade off of increased time and difficulty in development. You say you're doing things like text file processing, but what you omit is how much text file proc...
Setting the default value of a function input to equal another input in Python
3,534,371
12
2010-08-20T19:49:20Z
3,534,389
19
2010-08-20T19:51:53Z
[ "python", "function", "default-value", "keyword-argument" ]
Consider the following function, which does not work in Python, but I will use to explain what I need to do. ``` def exampleFunction(a, b, c = a): ...function body... ``` That is I want to assign to variable `c` the same value that variable `a` would take, unless an alternative value is specified. The above code ...
``` def exampleFunction(a, b, c = None): if c is None: c = a ...function body... ``` The default value for the keyword argument can't be a variable (if it is, it's converted to a fixed value when the function is defined.) Commonly used to pass arguments to a main function: ``` def main(argv=None): ...
Setting the default value of a function input to equal another input in Python
3,534,371
12
2010-08-20T19:49:20Z
3,534,401
12
2010-08-20T19:52:55Z
[ "python", "function", "default-value", "keyword-argument" ]
Consider the following function, which does not work in Python, but I will use to explain what I need to do. ``` def exampleFunction(a, b, c = a): ...function body... ``` That is I want to assign to variable `c` the same value that variable `a` would take, unless an alternative value is specified. The above code ...
This general pattern is probably the best and most readable: ``` def exampleFunction(a, b, c = None): if c is None: c = a ... ``` You have to be careful that `None` is not a valid state for `c`. If you want to support 'None' values, you can do something like this: ``` def example(a, b, *args, **kwar...
Python regex, matching pattern over multiple lines.. why isn't this working?
3,534,507
7
2010-08-20T20:09:56Z
3,534,554
9
2010-08-20T20:16:42Z
[ "python", "regex", "parsing" ]
I know that for parsing I should ideally remove all spaces and linebreaks but I was just doing this as a quick fix for something I was trying and I can't figure out why its not working.. I have wrapped different areas of text in my document with the wrappers like "####1" and am trying to parse based on this but its jus...
Try `re.findall(r"####(.*?)\s(.*?)\s####", string, re.DOTALL)` (works with `re.compile` too, of course). This regexp will return tuples containing the number of the section and the section content. For your example, this will return `[('1', 'ttteest'), ('2', ' \n\nttest')]`. (BTW: your example won't run, for multili...
Python regex, matching pattern over multiple lines.. why isn't this working?
3,534,507
7
2010-08-20T20:09:56Z
3,534,555
14
2010-08-20T20:16:45Z
[ "python", "regex", "parsing" ]
I know that for parsing I should ideally remove all spaces and linebreaks but I was just doing this as a quick fix for something I was trying and I can't figure out why its not working.. I have wrapped different areas of text in my document with the wrappers like "####1" and am trying to parse based on this but its jus...
Multiline doesn't mean `.` will match line return, it means that `^` and `$` are limited to lines only > re.M > re.MULTILINE > > When specified, the pattern character '^' matches at the beginning of the string and at the >beginning of each line (immediately following each newline); and the pattern character '$' >match...
python equivalent to perl's qw()
3,534,714
16
2010-08-20T20:37:14Z
3,534,792
19
2010-08-20T20:47:31Z
[ "python", "perl", "quotes" ]
I do this a lot in Perl: ``` printf "%8s %8s %8s\n", qw(date price ret); ``` However, the best I can come up with in Python is ``` print '%8s %8s %8s' % (tuple("date price ret".split())) ``` I'm just wondering if there is a more elegant way of doing it? I'm fine if you tell me that's it and no improvement can be ma...
Well, there's definitely no way to do exactly what you can do in Perl, because Python will complain about undefined variable names and a syntax error (missing comma, perhaps). But I would write it like this (in Python 2.X): ``` print '%8s %8s %8s' % ('date', 'price', 'ret') ``` If you're really attached to Perl's syn...
python equivalent to perl's qw()
3,534,714
16
2010-08-20T20:37:14Z
3,538,042
9
2010-08-21T15:32:43Z
[ "python", "perl", "quotes" ]
I do this a lot in Perl: ``` printf "%8s %8s %8s\n", qw(date price ret); ``` However, the best I can come up with in Python is ``` print '%8s %8s %8s' % (tuple("date price ret".split())) ``` I'm just wondering if there is a more elegant way of doing it? I'm fine if you tell me that's it and no improvement can be ma...
"date price ret".split()
Unpythonic way of printing variables in Python?
3,534,803
6
2010-08-20T20:48:40Z
3,534,865
9
2010-08-20T20:58:39Z
[ "python" ]
Someone has recently demonstrated to me that we can print variables in Python like how Perl does. Instead of: ``` print("%s, %s, %s" % (foo, bar, baz)) ``` we could do: ``` print("%(foo)s, %(bar)s, %(baz)s" % locals()) ``` Is there a less hacky looking way of printing variables in Python like we do in Perl? I thin...
The only other way would be to use the Python 2.6+/3.x [`.format()`](http://docs.python.org/library/string.html#formatstrings) method for string formatting: ``` # dict must be passed by reference to .format() print("{foo}, {bar}, {baz}").format(**locals()) ``` Or referencing specific variables by name: ``` # Python ...
Select Children of an Object With ForeignKey in Django?
3,535,615
5
2010-08-20T23:47:34Z
3,535,668
12
2010-08-21T00:00:12Z
[ "python", "django" ]
I'm *brand new* to Django, so the answer to this is probably very simple. However, I can't figure it out. Say I have two bare-bones Models. ``` class Blog(models.Model): title = models.CharField(max_length=160) text = models.TextField() class Comment(models.Model): blog = models.ForeignKey(Blog) text...
to follow foreign keys 'backwards' you use ``` blog.comment_set.all() ```
How to rename a directory in Mercurial and continue to track all file changes
3,535,676
28
2010-08-21T00:03:47Z
3,535,731
35
2010-08-21T00:27:11Z
[ "python", "mercurial" ]
I decided to rename some directories in my home/hobby Python package (`doc` to `docs`, `test` to `tests`, `util` to `utils`) because, now that I've thought more about it, I think the new names are more appropriate. My general thinking now is that if containers are named after their contents their names should be plural...
Since you've already renamed the directories, this is perfectly OK. (It would have saved you a manual step if you'd let Mercurial rename them for you: `hg rename doc docs`, etc. instead of doing it yourself then letting Mercurial know about it). If you don't have any other files to check in, the `hg addremove` is supe...
How to rename a directory in Mercurial and continue to track all file changes
3,535,676
28
2010-08-21T00:03:47Z
3,536,777
15
2010-08-21T07:28:11Z
[ "python", "mercurial" ]
I decided to rename some directories in my home/hobby Python package (`doc` to `docs`, `test` to `tests`, `util` to `utils`) because, now that I've thought more about it, I think the new names are more appropriate. My general thinking now is that if containers are named after their contents their names should be plural...
Mercurial has no concept of directories; it treats everything (files and directories) as files. Also, I usually never rename files or directories manually; I just use > hg rename old-name new-name I suggest you do that too. Mercurial offers a rename-tracking feature, which means that mercurial can trace the complete...
How to rename a directory in Mercurial and continue to track all file changes
3,535,676
28
2010-08-21T00:03:47Z
6,604,103
9
2011-07-06T23:10:32Z
[ "python", "mercurial" ]
I decided to rename some directories in my home/hobby Python package (`doc` to `docs`, `test` to `tests`, `util` to `utils`) because, now that I've thought more about it, I think the new names are more appropriate. My general thinking now is that if containers are named after their contents their names should be plural...
One reason to use --after instead of renaming with hg is if you are using a refactoring tool that does more than just rename e.g. also fixes references.
How to change a module variable from another module?
3,536,620
32
2010-08-21T06:34:37Z
3,536,638
28
2010-08-21T06:41:17Z
[ "python", "import", "module" ]
Suppose I have a package named `bar`, and it contains `bar.py`: ``` a = None def foobar(): print a ``` and `__init__.py`: ``` from bar import a, foobar ``` Then I execute this script: ``` import bar print bar.a bar.a = 1 print bar.a bar.foobar() ``` Here's what I expect: ``` None 1 1 ``` Here's what I get...
you are using `from bar import a`. `a` becomes a symbol in the global scope of the importing module (or whatever scope the import statement occurs in). So when you assign a new value to `a`, you just change which value `a` points too, not the actual value. try to import `bar.py` directly with `import bar` in `__init__....
How to change a module variable from another module?
3,536,620
32
2010-08-21T06:34:37Z
3,537,045
8
2010-08-21T09:05:43Z
[ "python", "import", "module" ]
Suppose I have a package named `bar`, and it contains `bar.py`: ``` a = None def foobar(): print a ``` and `__init__.py`: ``` from bar import a, foobar ``` Then I execute this script: ``` import bar print bar.a bar.a = 1 print bar.a bar.foobar() ``` Here's what I expect: ``` None 1 1 ``` Here's what I get...
One source of difficulty with this question is that you have a program named `bar/bar.py`, so that `import bar` imports either `bar/__init__.py` or `bar/bar.py`, depending on where it is done, which makes it a little cumbersome to track which `a` is `bar.a`. Here is how it works: The key to understanding what happens...
Multiplying a string with a number in python
3,536,996
13
2010-08-21T08:50:59Z
3,537,017
23
2010-08-21T08:57:14Z
[ "python" ]
I need a string consisting of a repetition of a particular character. At the Python console, if I type : ``` n = '0'*8 ``` then n gets assigned a string consisting of 8 zeroes, which is what I expect. But, if I have the same in a Python program (`.py` file), then the program aborts with an error saying `can't mult...
You get that error because - in your program - the 8 is actually a string, too. ``` >>> '0'*8 '00000000' >>> '0'*'8' # note the ' around 8 (I spare you the traceback) TypeError: can't multiply sequence by non-int of type 'str' ```
Multiplying a string with a number in python
3,536,996
13
2010-08-21T08:50:59Z
3,537,023
9
2010-08-21T08:58:51Z
[ "python" ]
I need a string consisting of a repetition of a particular character. At the Python console, if I type : ``` n = '0'*8 ``` then n gets assigned a string consisting of 8 zeroes, which is what I expect. But, if I have the same in a Python program (`.py` file), then the program aborts with an error saying `can't mult...
I could bet you're using `raw_input()` to read the value which multiplies the string. You should use `input()` instead to read the value as an integer, not a string.
Python Reverse Find in String
3,537,717
14
2010-08-21T12:59:08Z
3,537,726
19
2010-08-21T13:01:12Z
[ "python", "string", "find", "reverse" ]
I have a string and an arbitrary index into the string. I want find the first occurrence of a substring before the index. An example: I want to find the index of the 2nd I by using the index and `str.rfind()` ``` s = "Hello, I am 12! I like plankton but I don't like Baseball." index = 34 #points to the 't' in 'but' i...
Your call told rfind to *start looking* at index 34. You want to use the [rfind overload](http://docs.python.org/library/stdtypes.html#str.rfind) that takes a string, a start, and an end. Tell it to start at the beginning of the string (`0`) and stop looking at `index`: ``` >>> s = "Hello, I am 12! I like plankton but...
Many-to-many data structure in Python
3,538,322
6
2010-08-21T17:27:06Z
3,538,340
16
2010-08-21T17:33:54Z
[ "python", "data-structures", "many-to-many" ]
I have a data set of books and authors, with a many-to-many relationship. There are about 10^6 books and 10^5 authors, with an average of 10 authors per book. I need to perform a series of operations on the data set, such as counting the number of books by each author or deleting all books by a certain author from th...
[sqlite3](http://docs.python.org/library/sqlite3.html) (or any other good relational DB, but `sqlite` comes with Python and is handier for such a reasonably small set of data) seems the right approach for your task. If you'd rather not learn SQL, [SQLAlchemy](http://www.sqlalchemy.org/) is a popular "wrapper" over rela...
Python: rewinding one line in file when iterating with f.next()
3,539,107
6
2010-08-21T21:40:37Z
3,539,132
12
2010-08-21T21:46:56Z
[ "python", "next", "seek" ]
Python's f.tell doesn't work as I expected when you iterate over a file with f.next(): ``` >>> f=open(".bash_profile", "r") >>> f.tell() 0 >>> f.next() "alias rm='rm -i'\n" >>> f.tell() 397 >>> f.next() "alias cp='cp -i'\n" >>> f.tell() 397 >>> f.next() "alias mv='mv -i'\n" >>> f.tell() 397 ``` Looks like it gives yo...
No. I would make an adapter that largely forwarded all calls, but kept a copy of the last line when you did `next` and then let you call a different method to make that line pop out again. I would actually make the adapter be an adapter that could wrap any iterable instead of a wrapper for file because that sounds lik...
Using Cython with Django. Does it make sense?
3,539,120
17
2010-08-21T21:44:46Z
3,539,136
15
2010-08-21T21:47:51Z
[ "python", "django", "cython" ]
Is it possible to optimize speed of a mission critical application developed in Django with Cython Sorry in advance if it doesn't make sense......as i am new to django. Recently i have read on the internet that you can use cython and turn a python code to c like speed......so i was wondering is this possible with dja...
Well, yes, but most things a web app does won't really benefit from this sort of change unless you have firm proof that it will. Profile twice, optimize once.
Using Cython with Django. Does it make sense?
3,539,120
17
2010-08-21T21:44:46Z
3,539,374
19
2010-08-21T22:57:23Z
[ "python", "django", "cython" ]
Is it possible to optimize speed of a mission critical application developed in Django with Cython Sorry in advance if it doesn't make sense......as i am new to django. Recently i have read on the internet that you can use cython and turn a python code to c like speed......so i was wondering is this possible with dja...
> Is it possible to optimize speed of a mission critical application developed in Django with Cython It's doubtful. Most of a web application response time is the non-HTML elements that must be downloaded separately. The usual rule of thumb is 8 static files per HTML page. (.CSS, .JS, images, etc.) Since none of tha...
Using Cython with Django. Does it make sense?
3,539,120
17
2010-08-21T21:44:46Z
6,337,953
10
2011-06-14T00:41:37Z
[ "python", "django", "cython" ]
Is it possible to optimize speed of a mission critical application developed in Django with Cython Sorry in advance if it doesn't make sense......as i am new to django. Recently i have read on the internet that you can use cython and turn a python code to c like speed......so i was wondering is this possible with dja...
Conceptually what you are after is possible, but you are looking in the wrong direction. You really should be interested in PyPy, which is an extremely promising technology for the Django (and Python) community. Benchmarks of Django on PyPy already show a **12.5X speed gain** when compared to normal Python. Now even t...
Constructing a random string
3,539,945
3
2010-08-22T03:05:17Z
3,539,954
7
2010-08-22T03:09:28Z
[ "python" ]
How to construct a string to have more than 5 characters and maximum of 15 characters using random function in python ``` import string letters = list(string.lowercase) ```
After the import and assignment you already have, assuming you want all possible lengths with the same probability: ``` import random length = random.randrange(5, 16) randstr = ''.join(random.choice(letters) for _ in range(length)) ```
How do I read a random line from one file in python?
3,540,288
17
2010-08-22T05:23:47Z
3,540,315
38
2010-08-22T05:35:59Z
[ "python" ]
Is there a built-in method to do it? If not how can I do this without costing too much overhead?
Not built-in, but algorithm `R(3.4.2)` (Waterman's "Reservoir Algorithm") from Knuth's "The Art of Computer Programming" is good (in a very simplified version): ``` import random def random_line(afile): line = next(afile) for num, aline in enumerate(afile): if random.randrange(num + 2): continue l...
How do I read a random line from one file in python?
3,540,288
17
2010-08-22T05:23:47Z
3,540,346
19
2010-08-22T05:47:34Z
[ "python" ]
Is there a built-in method to do it? If not how can I do this without costing too much overhead?
``` import random lines = open('file.txt').read().splitlines() myline =random.choice(lines) print(myline) ``` For very long file: seek to random place in file based on it's length and find two newline characters after position (or newline and end of file). Do again 100 characters before or from beginning of file if or...
Difference between random randint vs randrange
3,540,431
20
2010-08-22T06:18:28Z
3,540,456
26
2010-08-22T06:30:07Z
[ "python" ]
The only difference that I know between `randrange` and `randint` is that `randrange([start], stop[, step])` you can use the step and `random.randrange(0,1)` will not consider the last item, while `randint(0,1)` returns a choice inclusive of the last item. So, I can't find a reason for explain why `randrange(0,1)` doe...
The docs on randrange say: > `random.randrange([start], stop[, step])` > > Return a randomly selected element from `range(start, stop, step)`. **This is equivalent to `choice(range(start, stop, step))`**, but doesn’t actually build a range object. And range(start, stop) returns `[start, start+step, ..., stop-1]`, n...
Difference between random randint vs randrange
3,540,431
20
2010-08-22T06:18:28Z
26,817,613
8
2014-11-08T13:25:18Z
[ "python" ]
The only difference that I know between `randrange` and `randint` is that `randrange([start], stop[, step])` you can use the step and `random.randrange(0,1)` will not consider the last item, while `randint(0,1)` returns a choice inclusive of the last item. So, I can't find a reason for explain why `randrange(0,1)` doe...
<https://github.com/python/cpython/blob/master/Lib/random.py#L214>: ``` def randint(self, a, b): """Return random integer in range [a, b], including both end points. """ return self.randrange(a, b+1) ```
Python error "IOError: [Errno 2] No such file or directory" but file is there
3,541,109
4
2010-08-22T10:30:24Z
3,541,128
7
2010-08-22T10:34:55Z
[ "python", "file", "io" ]
I am trying to read a csv file and I am getting the error above but the file is there. The line giving the error is ``` infilequery = file('D:\x88_2.csv','rb') ``` and I get the error below. Traceback (most recent call last): File "C:\Python26\usrapply\_onemol2.py", line 14, in infilequery = file('D:\x88\_2.csv','rb...
Try ``` 'D:\\x88_2.csv' ``` The `\x88` is interpreted as the character at code point 0x88. Alternatively you could use raw string ``` r'D:\x88_2.csv' ``` or forward slash ``` 'D:/x88_2.csv' ```
Does readlines() return a list or an iterator in Python 3?
3,541,203
15
2010-08-22T10:55:49Z
3,541,231
17
2010-08-22T11:03:03Z
[ "python", "iterator", "python-3.x", "readlines" ]
I've read in "Dive into Python 3" that "The readlines() method now returns an iterator, so it is just as efficient as xreadlines() was in Python 2". See here: <http://diveintopython3.org/porting-code-to-python-3-with-2to3.html> . I'm not sure that it's true because they don't mention it here: <http://docs.python.org/re...
The readlines method doesn't return an iterator in Python 3, it returns a list ``` Help on built-in function readlines: readlines(...) Return a list of lines from the stream. ``` To check, just call it from an interactive session - it will return a list, rather than an iterator: ``` >>> type(f.readlines()) <cla...
Does readlines() return a list or an iterator in Python 3?
3,541,203
15
2010-08-22T10:55:49Z
3,541,234
14
2010-08-22T11:03:56Z
[ "python", "iterator", "python-3.x", "readlines" ]
I've read in "Dive into Python 3" that "The readlines() method now returns an iterator, so it is just as efficient as xreadlines() was in Python 2". See here: <http://diveintopython3.org/porting-code-to-python-3-with-2to3.html> . I'm not sure that it's true because they don't mention it here: <http://docs.python.org/re...
Like this: ``` Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> f = open('/junk/so/foo.txt') >>> type(f.readlines()) <class 'list'> >>> help(f.readlines) Help on built-in function readlines: readlines(...) ...
What substitutes xreadlines() in Python 3?
3,541,274
8
2010-08-22T11:17:57Z
3,541,282
11
2010-08-22T11:22:08Z
[ "python", "iterator", "python-3.x", "readlines" ]
In Python 2, file objects had an xreadlines() method which returned an iterator that would read the file one line at a time. In Python 3, the xreadlines() method no longer exists, and realines() still returns a list (not an iterator). Does Python 3 has something similar to xreadlines()? I know I can do ``` for line i...
The file object itself is already an iterable. ``` >>> f = open('1.txt') >>> f <_io.TextIOWrapper name='1.txt' encoding='UTF-8'> >>> next(f) '1,B,-0.0522642316338,0.997268450092\n' >>> next(f) '2,B,-0.081127897359,2.05114559572\n' ``` --- [Use `itertools.islice`](http://docs.python.org/py3k/library/itertools.html) t...
Is it safe to use ComputedProperty?
3,541,398
4
2010-08-22T12:03:36Z
3,541,497
7
2010-08-22T12:35:01Z
[ "python", "google-app-engine" ]
I need support for computed properties in App Engine. I downloaded the latest source release to try and implement them myself. Whilst going through code, I came across a property class that already seems to do *exactly* what I need. ``` class ComputedProperty(Property): """Property used for creating properties deriv...
`ComputedProperty` seems to be a "port" (for lack of a better word) of a custom property class named [`DerivedProperty` from Nick Johnson's blog](http://blog.notdot.net/2009/9/Custom-Datastore-Properties-1-DerivedProperty). Since Nick's blog entry shows how easy it can be to create a custom datastore `Property` class,...
Create launchable GUI script from Python setuptools (without console window!)
3,542,119
5
2010-08-22T15:51:47Z
3,542,410
9
2010-08-22T17:06:40Z
[ "python", "setuptools", "distutils" ]
The way I currently add an executable for my Python-based GUI is this: ``` setup( # ... entry_points = {"gui_scripts" : ['frontend = myfrontendmodule.launcher:main']}, # ... ) ``` On Windows, this will create "frontend.exe" and "frontend-script.pyw" in Python's scripts folder (using Python 2.6...
Alright, I investigated a bit in the setuptools source code and it all boils down to a bug in setuptools (easy\_install.py): ``` # On Windows/wininst, add a .py extension and an .exe launcher if group=='gui_scripts': ext, launcher = '-script.pyw', 'gui.exe' old = ['.pyw'] new_header = re.sub('(?i)python.ex...
What's this text encoding?
3,542,842
4
2010-08-22T18:48:06Z
3,542,847
14
2010-08-22T18:49:11Z
[ "python", "encoding", "gmail", "character", "imaplib" ]
I used Python's imaplib to pull mail from a gmail account... but I got an email with this confusing text body: ``` > RGF0ZSBldCBoZXVyZTogICAgICAgICAgICAgICAgICAgICAgICAgICAyMi8wOC8yMDEwIDE0 > OjMzOjAzIEdNVCBVbmtub3duDQpQcsOpbm9tOiAgICAgICAgICAgICAgICAgICAgICAgICAg > ICAgICAgICAgamFjaW50bw0KTm9tOiAgICAgICAgICAgICAgICAg...
It looks like base64. In Python you can either use [`base64.b64decode`](http://docs.python.org/library/base64.html#base64.b64decode) or [`str.decode('base64')`](http://docs.python.org/library/stdtypes.html#str.decode). ``` message = ''' RGF0ZSBldCBoZXVyZTogICAgICAgICAgICAgICAgICAgICAgICAgICAyMi8wOC8yMDEwIDE0 OjMzOjAzI...
Python, opposite function urllib.urlencode
3,542,881
71
2010-08-22T18:59:15Z
3,542,894
101
2010-08-22T19:02:55Z
[ "python", "urllib" ]
How can I convert data after processing `urllib.urlencode` to dict? `urllib.urldecode` does not exist.
As [the docs](http://docs.python.org/library/urllib.html#urllib.urlencode) for `urlencode` say, > The urlparse module provides the > functions parse\_qs() and parse\_qsl() > which are used to parse query strings > into Python data structures. (In older Python releases, they were in the `cgi` module). So, for example:...
Python, opposite function urllib.urlencode
3,542,881
71
2010-08-22T18:59:15Z
10,183,327
9
2012-04-17T00:02:21Z
[ "python", "urllib" ]
How can I convert data after processing `urllib.urlencode` to dict? `urllib.urldecode` does not exist.
[Python 3 code](http://docs.python.org/py3k/library/urllib.parse.html) for Alex's solution: ``` >>> import urllib.parse >>> d = {'a':'b', 'c':'d'} >>> s = urllib.parse.urlencode(d) >>> s 'a=b&c=d' >>> d1 = urllib.parse.parse_qs(s) >>> d1 {'a': ['b'], 'c': ['d']} ``` The alternative: ``` >>> sq = urllib.parse.parse_q...
Python, opposite function urllib.urlencode
3,542,881
71
2010-08-22T18:59:15Z
22,046,096
13
2014-02-26T15:36:32Z
[ "python", "urllib" ]
How can I convert data after processing `urllib.urlencode` to dict? `urllib.urldecode` does not exist.
[urllib.unquote\_plus()](http://docs.python.org/2/library/urllib.html#urllib.unquote_plus) does what you want. It Replace %xx escapes by their single-character equivalent and replaces plus signs with spaces. Example: unquote\_plus('/%7Ecandidates/?name=john+connolly') yields '/~candidates/?name=john connolly'.
Django annotate groupings by month
3,543,379
15
2010-08-22T21:01:42Z
3,543,584
15
2010-08-22T21:54:20Z
[ "python", "django" ]
I have a very basic model: ``` class Link(models.Model): title = models.CharField(max_length=250, null=False) user = models.ForeignKey(User) url = models.CharField(max_length=250, blank=True, null=True) link_count = models.IntegerField(default=0) pub_date = models.DateField(auto_now_add=True) u...
If you're on PostgreSQL, the following might work: ``` from django.db.models import Count Link.objects.extra(select={'month': 'extract( month from pub_date )'}).values('month').annotate(dcount=Count('pub_date')) ``` I'm not sure how portable `extract` is across other databases.
Django annotate groupings by month
3,543,379
15
2010-08-22T21:01:42Z
4,095,397
13
2010-11-04T09:44:17Z
[ "python", "django" ]
I have a very basic model: ``` class Link(models.Model): title = models.CharField(max_length=250, null=False) user = models.ForeignKey(User) url = models.CharField(max_length=250, blank=True, null=True) link_count = models.IntegerField(default=0) pub_date = models.DateField(auto_now_add=True) u...
``` from django.db import connections from django.db.models import Count Link.objects.extra(select={'month': connections[Link.objects.db].ops.date_trunc_sql('month', 'pub_date')}).values('month').annotate(dcount=Count('pub_date')) ```
ASCII art in the optparse description
3,543,386
11
2010-08-22T21:03:14Z
3,543,465
10
2010-08-22T21:24:20Z
[ "python", "optparse", "ascii-art" ]
I'm making a shell script with the optparse module, jut for fun, so I wanted to print a nice ascii drawing in place of the description. Turns out that this code: ``` parser = optparse.OptionParser( prog='./spill.py', description=u''' / \ vvvvvvv /|__/| ...
The default formatter, `IndentedHelpFormatter`, calls this method: ``` def format_description(self, description): if description: return self._format_text(description) + "\n" else: return "" ``` If you subclass `IndentedHelpFormatter`, you can remove the `self._format_text` call which is caus...
Script won't run in Python3.0
3,543,453
4
2010-08-22T21:21:19Z
3,543,464
13
2010-08-22T21:24:19Z
[ "python", "python-3.x" ]
This script will run as expected and pass doctests without any errors in Python 2.6: ``` def num_even_digits(n): """ >>> num_even_digits(123456) 3 >>> num_even_digits(2468) 4 >>> num_even_digits(1357) 0 >>> num_even_digits(2) 1 >>> num_even_digits(20) 2 ...
I'm guessing you need `n //= 10` instead of `n /= 10`. In other words, you want to explictly specify integer division. Otherwise `1 / 10` will return `0.1` instead of `0`. Note that `//=` is valid python 2.x syntax, as well (well, starting with version ~2.3, I think...).
python regex match and replace
3,543,559
15
2010-08-22T21:47:26Z
3,543,586
18
2010-08-22T21:55:02Z
[ "python", "regex" ]
I need to find, process and remove (one by one) any substrings that match a rather long regex: ``` # p is a compiled regex # s is a string while 1: m = p.match(s) if m is None: break process(m.group(0)) #do something with the matched pattern s = re.sub(m.group(0), '', s) #remove it from strin...
The [re.sub](http://docs.python.org/library/re.html#re.sub) function can take a function as an argument so you can combine the replacement and processing steps if you wish: ``` # p is a compiled regex # s is a string def process_match(m): # Process the match here. return '' s = p.sub(process_match, s) ```
How do I clear all variables in the middle of a Python script?
3,543,833
31
2010-08-22T23:05:06Z
3,543,840
17
2010-08-22T23:07:38Z
[ "python", "clear" ]
I am looking for something similar to 'clear' in Matlab: A command/function which removes all variables from the workspace, releasing them from system memory. Is there such a thing in Python? EDIT: I want to write a script which at some point clears all the variables.
No, you are best off restarting the interpreter [Ipython](http://ipython.scipy.org) is an excellent replacement for the bundled interpreter and has the `%reset` command which usually works
How do I clear all variables in the middle of a Python script?
3,543,833
31
2010-08-22T23:05:06Z
3,543,866
21
2010-08-22T23:17:11Z
[ "python", "clear" ]
I am looking for something similar to 'clear' in Matlab: A command/function which removes all variables from the workspace, releasing them from system memory. Is there such a thing in Python? EDIT: I want to write a script which at some point clears all the variables.
The following sequence of commands does remove **every** name from the current module: ``` >>> import sys >>> sys.modules[__name__].__dict__.clear() ``` I doubt you actually DO want to do this, because "every name" includes all built-ins, so there's not much you can do after such a total wipe-out. Remember, in Python...
How do I clear all variables in the middle of a Python script?
3,543,833
31
2010-08-22T23:05:06Z
3,544,015
18
2010-08-23T00:14:39Z
[ "python", "clear" ]
I am looking for something similar to 'clear' in Matlab: A command/function which removes all variables from the workspace, releasing them from system memory. Is there such a thing in Python? EDIT: I want to write a script which at some point clears all the variables.
Write a function. Once you leave it all names inside disappear. It is very pointless to do this yourself in any kind of way. The concept is called [namespace](http://docs.python.org/3.3/tutorial/classes.html#python-scopes-and-namespaces) and it's so good, it made it into the [Zen of Python](http://www.python.org/dev/p...
About the PIL Error -- IOError: decoder zip not available
3,544,155
61
2010-08-23T01:14:20Z
3,544,159
11
2010-08-23T01:17:23Z
[ "python", "python-imaging-library" ]
I am getting the: ``` IOError: decoder zip not available ``` when I try to draw an image and save to a jpeg in PIL. Any thoughts on how to resolve this? PIL has worked fine for me in the past, when it comes to viewing/uploading images.
It likely only needs the zip decoder to save the jpeg. I think I needed to follow these steps in OS X to preview jpegs. It probably means you need to: * Download [the PIL source](http://effbot.org/downloads/Imaging-1.1.7.tar.gz). * Download the zlib library. * [Point the PIL source to the zlib library.](http://effbot...
About the PIL Error -- IOError: decoder zip not available
3,544,155
61
2010-08-23T01:14:20Z
9,222,179
37
2012-02-10T03:08:50Z
[ "python", "python-imaging-library" ]
I am getting the: ``` IOError: decoder zip not available ``` when I try to draw an image and save to a jpeg in PIL. Any thoughts on how to resolve this? PIL has worked fine for me in the past, when it comes to viewing/uploading images.
The more detail installation PIL with zlib library in Ubuntu 64 bit : <http://obroll.com/install-python-pil-python-image-library-on-ubuntu-11-10-oneiric/> For the lazy (credits to @**meawoppl** for the `apt-get`): ``` $ sudo apt-get install libjpeg-dev zlib1g-dev ```
About the PIL Error -- IOError: decoder zip not available
3,544,155
61
2010-08-23T01:14:20Z
12,359,864
111
2012-09-10T21:38:33Z
[ "python", "python-imaging-library" ]
I am getting the: ``` IOError: decoder zip not available ``` when I try to draw an image and save to a jpeg in PIL. Any thoughts on how to resolve this? PIL has worked fine for me in the past, when it comes to viewing/uploading images.
``` sudo pip uninstall PIL sudo pip install pillow ``` ^^ fixed it for me. [Pillow](http://pypi.python.org/pypi/Pillow/) is a fork of PIL that is compatible with pip/setuptools and gets a little better maintenance. I haven't seen any API differences yet. Edit: There is one notable API difference. PIL exposes Image a...
About the PIL Error -- IOError: decoder zip not available
3,544,155
61
2010-08-23T01:14:20Z
21,128,717
16
2014-01-15T03:43:11Z
[ "python", "python-imaging-library" ]
I am getting the: ``` IOError: decoder zip not available ``` when I try to draw an image and save to a jpeg in PIL. Any thoughts on how to resolve this? PIL has worked fine for me in the past, when it comes to viewing/uploading images.
I encountered this problem on a **64bit ubuntu 13.04 desktop version** and here is how I resolved it. try to reinstall PIL, and pay attention to the output info after you reinstalled: ``` --------------------------------------------------------------------- PIL 1.1.7 SETUP SUMMARY ------------------------------------...
conditional `ctypedef` with Cython
3,544,240
6
2010-08-23T01:44:14Z
3,544,420
9
2010-08-23T02:47:02Z
[ "python", "c", "cython" ]
I need access to the `uint64_t` typedef from `stdint.h` in some wrapper code that I'm writing and I can't figure out how to get it done. The problem is that from what I can tell from the docs, my `ctypedef` will have to take the form: ``` ctypedef unsigned long uint64_t ``` or ``` ctypedef unsigned long long uint64_...
``` cdef extern from "stdint.h": ctypedef unsigned long long uint64_t ``` Any `ctypedef` that's `extern`'d won't have a typedef generated in the .c file. Cython will include `stdint.h` and your C compiler will use the actual typedef from there. The only thing that the type provided matters for is when cython gene...
Quickly find differences between two large text files
3,544,331
9
2010-08-23T02:17:43Z
3,544,342
7
2010-08-23T02:21:02Z
[ "python", "file", "text", "diff", "compare" ]
I have two 3GB text files, each file has around 80 million lines. And they share 99.9% identical lines (file A has 60,000 unique lines, file B has 80,000 unique lines). How can I quickly find those unique lines in two files? Is there any ready-to-use command line tools for this? I'm using Python but I guess it's less ...
If order matters, try the `comm` utility. If order doesn't matter, `sort file1 file2 | uniq -u`.
Uninstall python built from source?
3,544,378
26
2010-08-23T02:32:16Z
3,544,440
21
2010-08-23T02:52:19Z
[ "python", "linux", "ubuntu", "python-2.x" ]
I've installed python 2.6 from source, and somehow later mistakenly installed another python 2.6 from a package manager too. I can't find a way to uninstall a python that was built from source, is this possible/easy? Running ubuntu 10.04 Thanks.
You can use checkinstall to remove Python. The idea is: 1. Install checkinstall 2. Use checkinstall to make a deb of your Python installation 3. Use `dpkg -r` to remove the deb. See [this post](http://ubuntuforums.org/showthread.php?p=7635985#post7635985) for more details. PS. Note that Ubuntu must always h...
Numpy for R user?
3,545,057
5
2010-08-23T06:01:55Z
3,546,066
10
2010-08-23T09:03:46Z
[ "python", "numpy", "scipy" ]
long-time R and Python user here. I use R for my daily data analysis and Python for tasks heavier on text processing and shell-scripting. I am working with increasingly large data sets, and these files are often in binary or text files when I get them. The type of things I do normally is to apply statistical/machine le...
I use NumPy daily and R nearly so. For heavy number crunching, i prefer NumPy to R by a large margin (including R packages, like 'Matrix') I find the syntax cleaner, the function set larger, and computation is quicker (although i don't find R slow by any means). NumPy's Broadcasting functionality for instance, i do no...
Numpy for R user?
3,545,057
5
2010-08-23T06:01:55Z
3,548,160
10
2010-08-23T13:46:54Z
[ "python", "numpy", "scipy" ]
long-time R and Python user here. I use R for my daily data analysis and Python for tasks heavier on text processing and shell-scripting. I am working with increasingly large data sets, and these files are often in binary or text files when I get them. The type of things I do normally is to apply statistical/machine le...
R's strength when looking for an environment to do machine learning and statistics is most certainly the diversity of its libraries. To my knowledge, SciPy + SciKits cannot be a replacement for CRAN. Regarding memory usage, R is using a pass-by-value paradigm while Python is using pass-by-reference. Pass-by-value can ...
Simulate Mouse Clicks on Python
3,545,230
30
2010-08-23T06:42:29Z
3,572,488
13
2010-08-26T06:17:11Z
[ "python", "linux", "mouse", "cursor", "wiimote" ]
I'm currently in the process of making my Nintendo Wiimote (Kinda sad actually) to work with my computer as a mouse. I've managed to make the nunchuk's stick control actually move the mouse up and down, left and right on the screen! This was so exciting. Now I'm stuck. I want to left/right click on things via python w...
python-uinput is very easy to use. <http://tjjr.fi/software/python-uinput/> Here's an example <https://github.com/tuomasjjrasanen/python-uinput/blob/master/examples/mouse.py>
Simulate Mouse Clicks on Python
3,545,230
30
2010-08-23T06:42:29Z
15,994,043
20
2013-04-13T23:25:39Z
[ "python", "linux", "mouse", "cursor", "wiimote" ]
I'm currently in the process of making my Nintendo Wiimote (Kinda sad actually) to work with my computer as a mouse. I've managed to make the nunchuk's stick control actually move the mouse up and down, left and right on the screen! This was so exciting. Now I'm stuck. I want to left/right click on things via python w...
You can use [PyMouse](https://github.com/pepijndevos/PyMouse) which has now merged with [PyUserInput](https://github.com/SavinaRoja/PyUserInput). I installed it via pip: apt-get install python-pip pip install pymouse In some cases it used the cursor and in others it simulated mouse events without the cursor. ``` fr...
How can I get dictionary key as variable directly in Python (not by searching from value)?
3,545,331
91
2010-08-23T07:01:32Z
3,545,353
109
2010-08-23T07:04:48Z
[ "python", "dictionary", "key" ]
Sorry for this basic question but my searches on this are not turning up anything other than how to get a dictionary's key based on its value which I would prefer not to use as I simply want the text/name of the key and am worried that searching by value may end up returning 2 or more keys if the dictionary has a lot o...
You should iterate over keys with: ``` for key in mydictionary: print "key: %s , value: %s" % (key, mydictionary[key]) ```
How can I get dictionary key as variable directly in Python (not by searching from value)?
3,545,331
91
2010-08-23T07:01:32Z
3,545,355
53
2010-08-23T07:05:28Z
[ "python", "dictionary", "key" ]
Sorry for this basic question but my searches on this are not turning up anything other than how to get a dictionary's key based on its value which I would prefer not to use as I simply want the text/name of the key and am worried that searching by value may end up returning 2 or more keys if the dictionary has a lot o...
If you want to print key and value, use the following: ``` for key, value in my_dict.iteritems(): print key, value ```
How can I get dictionary key as variable directly in Python (not by searching from value)?
3,545,331
91
2010-08-23T07:01:32Z
3,545,364
42
2010-08-23T07:06:40Z
[ "python", "dictionary", "key" ]
Sorry for this basic question but my searches on this are not turning up anything other than how to get a dictionary's key based on its value which I would prefer not to use as I simply want the text/name of the key and am worried that searching by value may end up returning 2 or more keys if the dictionary has a lot o...
> The reason for this is that I am printing these out to a document and I want to use the key name and the value in doing this Based on the above requirement this is what I would suggest: ``` keys = mydictionary.keys() keys.sort() for each in keys: print "%s: %s" % (each, mydictionary.get(each)) ```
How can I get dictionary key as variable directly in Python (not by searching from value)?
3,545,331
91
2010-08-23T07:01:32Z
31,607,151
8
2015-07-24T09:39:50Z
[ "python", "dictionary", "key" ]
Sorry for this basic question but my searches on this are not turning up anything other than how to get a dictionary's key based on its value which I would prefer not to use as I simply want the text/name of the key and am worried that searching by value may end up returning 2 or more keys if the dictionary has a lot o...
If the dictionary contains one pair like this: ``` d = {'age':24} ``` then you can get as ``` field, value = d.items()[0] ```
How much overhead do decorators add to Python function calls
3,545,690
17
2010-08-23T08:06:08Z
3,546,120
12
2010-08-23T09:11:45Z
[ "python", "performance", "decorator" ]
I've been playing around with a timing decorator for my pylons app to provide on the fly timing info for specific functions. I've done this by creating a decorator & simply attaching it to any function in the controller I want timed. It's been pointed out however that decorators could add a fair amount of overhead to ...
The overhead added by using a decorator should be just one extra function call. The work being done by the decorator isn't part of the overhead as your alternative is to add the equivalent code to the decorated object. So it's possible that the decorate function takes twice as long to run, but that's because the deco...
simultaneous files downloading in python and qt
3,546,534
2
2010-08-23T10:07:11Z
3,546,857
7
2010-08-23T10:55:09Z
[ "python", "multithreading", "qt", "download" ]
In my program I need to download 3-4 files simultaneously (from different servers which are quite slow). I'm aware of the solution involving python threads or qt threads, but I'm wondering: since it seems to be a quite common task, maybe there's a library which I feed with urls and simply receive the files? Thanks in a...
Yes, there is one - pycurl. Its not 'simply', since curl is low-level, but it does exactly what you need - you provide it some urls and it downloads then simultaneously and asynchronously. ``` import pycurl from StringIO import StringIO def LoadMulti(urls): m = pycurl.CurlMulti() handles = {} for url in ...
What encoding do normal python strings use?
3,547,534
9
2010-08-23T12:33:13Z
3,548,031
21
2010-08-23T13:32:12Z
[ "python", "encoding" ]
i know that django uses unicode strings all over the framework instead of normal python strings. what encoding are normal python strings use ? and why don't they use unicode?
Normal Python strings (Python 2.x `str`) don't have an encoding: they are raw data. In Python 3 these are called "bytes" which is an accurate description, as they are simply sequences of bytes, which can be text encoded in *any* encoding (several are common!) or non-textual data altogether. **For representing *text*, ...
What encoding do normal python strings use?
3,547,534
9
2010-08-23T12:33:13Z
3,549,611
12
2010-08-23T16:32:06Z
[ "python", "encoding" ]
i know that django uses unicode strings all over the framework instead of normal python strings. what encoding are normal python strings use ? and why don't they use unicode?
Hey! I'd like to add some stuff to other answers, unfortunately I don't have enough rep yet to do that properly :-( FWIW, Mike Graham's post is pretty good and that's probably what you should be reading first. Here's a few comments: 1. The need to prefix unicode literals with "u" in 2.x is pretty easily removed in r...
Download, extract and read a gzip file in Python
3,548,495
6
2010-08-23T14:28:23Z
3,548,609
9
2010-08-23T14:41:21Z
[ "python" ]
I'd like to download, extract and iterate over a text file in Python without having to create temporary files. basically, this pipe, but in python ``` curl ftp://ftp.theseed.org/genomes/SEED/SEED.fasta.gz | gunzip | processing step ``` Here's my code: ``` def main(): import urllib import gzip # Downloa...
Just `gzip.GzipFile(fileobj=handle)` and you'll be on your way -- in other words, it's not really true that "the Gzip library only accepts filenames as arguments and not handles", you just have to use the `fileobj=` named argument.
Python + JSON, what happened to None?
3,548,635
5
2010-08-23T14:44:32Z
3,548,740
13
2010-08-23T14:56:24Z
[ "python", "json", "dictionary" ]
Dumping and loading a dict with None as key, results in a dict with "null" as the key. Values are un-affected, but things get even worse if a string-key "null" actually exists. What am I doing wrong here? Why cant i serialize/deserialize a dict with "None" keys? # Example ``` >>> json.loads(json.dumps({'123':None, ...
JSON objects are maps of *strings* to values. If you try to use another type of key, they'll get converted to strings. ``` >>> json.loads(json.dumps({123: None})) {'123': None} >>> json.loads(json.dumps({None: None})) {'null': None} ```
How to replace (or strip) an extension from a filename in Python?
3,548,673
23
2010-08-23T14:49:25Z
3,548,689
45
2010-08-23T14:51:09Z
[ "python", "scons" ]
Is there a built-in function in Python that would replace (or remove, whatever) the extension of a filename (if it has one) ? Example: ``` print replace_extension('/home/user/somefile.txt', '.jpg') ``` In my example: `/home/user/somefile.txt` would become `/home/user/somefile.jpg` I don't know if it matters, but I ...
Try [os.path.splitext](http://docs.python.org/library/os.path.html#os.path.splitext) it should do what you want. ``` import os print os.path.splitext('/home/user/somefile.txt')[0]+'.jpg' ```
How to replace (or strip) an extension from a filename in Python?
3,548,673
23
2010-08-23T14:49:25Z
3,548,744
14
2010-08-23T14:56:51Z
[ "python", "scons" ]
Is there a built-in function in Python that would replace (or remove, whatever) the extension of a filename (if it has one) ? Example: ``` print replace_extension('/home/user/somefile.txt', '.jpg') ``` In my example: `/home/user/somefile.txt` would become `/home/user/somefile.jpg` I don't know if it matters, but I ...
As @jethro said, `splitext` is the neat way to do it. But in this case, it's pretty easy to split it yourself, since the extension *must be* the part of the filename coming after the final period: ``` filename = '/home/user/somefile.txt' print( filename.rsplit( ".", 1 )[ 0 ] ) # '/home/user/somefile' ``` The `rsplit`...
What is the best escape character strategy for Python/MySQL combo?
3,549,691
4
2010-08-23T16:41:19Z
3,549,741
10
2010-08-23T16:46:39Z
[ "python", "mysql", "escaping" ]
This is my query. ``` cursor2.execute("update myTable set `"+ str(row[1]) +"` = \"'" + str(row[3]) +"'\" where ID = '"+str(row[0])+"'") ``` It is failing when row values have double quotes "some value". How do I escape all special characters?
Here is an example: ``` import MySQLdb column = str(MySQLdb.escape_string(row[1])) query = "update myTable set %(column)s = %%s where ID = %%s" % dict(column = column) cursor2.execute(query, [row[3], row[0]]) ``` **Update** Here is a brief commentary: ``` column = str(MySQLdb.escape_string(row[1])) ``` Always a g...
What is the best escape character strategy for Python/MySQL combo?
3,549,691
4
2010-08-23T16:41:19Z
3,549,816
7
2010-08-23T16:55:50Z
[ "python", "mysql", "escaping" ]
This is my query. ``` cursor2.execute("update myTable set `"+ str(row[1]) +"` = \"'" + str(row[3]) +"'\" where ID = '"+str(row[0])+"'") ``` It is failing when row values have double quotes "some value". How do I escape all special characters?
You should learn to use query parameters: ``` colname = str(row[1]).replace("`", "\\`") sql = "update myTable set `%s` = :col1 WHERE ID = :id" % (colname) cursor2.execute(sql, {"col1":str(row[3]), "id":str(row[0])}) ```
python threading: memory model and visibility
3,549,833
14
2010-08-23T16:57:47Z
3,549,940
13
2010-08-23T17:11:39Z
[ "python", "multithreading", "memory-model" ]
Does python threading expose issues of memory visibility and statement reordering as Java does? Since I can't find any reference to a "Python Memory Model" or anything like that, despite the fact that lots of people are writing multithreaded Python code, I'm guessing that these gotchas don't exist here. No *volatile* k...
There is no formal model for Python's threading (hey, after all, there wasn't one for Java's for years... hopefully, one will also eventually be written for Python). In practice, no Python implementation performs any advanced optimization such as statement reordering or temporarily treating shared variables as thread-...