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 |
|---|---|---|---|---|---|---|---|---|---|
error: command 'gcc' failed with exit status 1 while installing eventlet | 11,094,718 | 121 | 2012-06-19T05:12:11Z | 11,094,752 | 257 | 2012-06-19T05:15:13Z | [
"python",
"ubuntu",
"eventlet"
] | I wanted to install `eventlet` on my system in order to have "Herd" for software deployment.. but the terminal is showing a gcc error:
```
root@agrover-OptiPlex-780:~# easy_install -U eventlet
Searching for eventlet
Reading http://pypi.python.org/simple/eventlet/
Reading http://wiki.secondlife.com/wiki/Eventle... | Your install is failing because you don't have the python development headers installed. You can do this through apt on ubuntu/debian with:
```
sudo apt-get install python-dev
```
for python3 use:
```
sudo apt-get install python3-dev
```
For eventlet you might also need the libevent libraries installed so if you ge... |
error: command 'gcc' failed with exit status 1 while installing eventlet | 11,094,718 | 121 | 2012-06-19T05:12:11Z | 27,719,200 | 10 | 2014-12-31T09:44:27Z | [
"python",
"ubuntu",
"eventlet"
] | I wanted to install `eventlet` on my system in order to have "Herd" for software deployment.. but the terminal is showing a gcc error:
```
root@agrover-OptiPlex-780:~# easy_install -U eventlet
Searching for eventlet
Reading http://pypi.python.org/simple/eventlet/
Reading http://wiki.secondlife.com/wiki/Eventle... | For fedora:
```
sudo yum install python-devel
sudo yum install libevent-devel
```
and finally:
```
easy_install gevent
``` |
How do you run the Tornado web server locally? | 11,094,920 | 7 | 2012-06-19T05:33:27Z | 11,100,116 | 17 | 2012-06-19T11:35:58Z | [
"python",
"tornado"
] | Is it possible to run Tornado such that it listens to a local port (e.g. localhost:8000). I can't seem to find any documentation explaining how to do this. | Add an address argument to Application.listen() or HTTPServer.listen().
It's documented [here (Application.listen)](http://www.tornadoweb.org/en/stable/web.html) and [here (TCPServer.listen)](http://www.tornadoweb.org/en/stable/tcpserver.html).
For example:
```
application = tornado.web.Application([
(r'/blah', ... |
Using the default firefox profile with selenium webdriver in python | 11,095,294 | 6 | 2012-06-19T06:08:15Z | 11,095,509 | 7 | 2012-06-19T06:27:29Z | [
"python",
"selenium",
"webdriver"
] | I know similar questions have been asked before, but I've tried many times and it still doesn't work for me.
I only have a default profile in firefox (called c1r3g2wi.default) and no other profiles. I want my firefox browser to start with this profile when I launch it using the selenium webdriver. How do I do this in ... | Ok, I just solved this by simply changing all the slashes in my file path from "\" to "/".
Never knew this would make a difference.
```
C:/Users/admin/AppData/Roaming/Mozilla/Firefox/Profiles/c1r3g2wi.default
``` |
Numpy difference between neighboring elements | 11,095,892 | 9 | 2012-06-19T06:59:48Z | 11,095,921 | 14 | 2012-06-19T07:01:57Z | [
"python",
"numpy"
] | I have algorithm of calculation of the difference between neighboring elements in pure python:
```
a = range(1000000) #it's numpy array in my case
prev = a[0]
b = [0, ]
for i in a[1:]:
b.append(i - prev)
prev = i
```
Is there any way to rewrite this functions with Numpy? | There is the [`diff`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.diff.html) method:
```
a = range(5) # python list of numpy array
np.diff(a)
```
returns
```
array([1, 1, 1, 1])
``` |
Set initial value to modelform in class based generic views | 11,096,617 | 14 | 2012-06-19T07:50:09Z | 11,096,714 | 26 | 2012-06-19T07:56:13Z | [
"python",
"django",
"django-forms",
"django-views",
"django-class-based-views"
] | I'm using Class based generic views, can anybody suggest me how can i set the initial values to update form?
I tried using get\_initial() method but didn't got any success. Following is the code which i tried
```
class IncidentUpdateView(UpdateView):
form_class = IncidentForm
form_class.initial = {"badg... | You should define a `get_initial` method which returns a dictionary that contains the initial values:
```
class IncidentUpdateView(UpdateView):
def get_initial(self):
return { 'value1': 'foo', 'value2': 'bar' }
```
Alternatively, you can define an `initial` value:
```
class IncidentUpdateView(UpdateView... |
Replace a string located between | 11,096,720 | 8 | 2012-06-19T07:56:42Z | 11,096,811 | 11 | 2012-06-19T08:02:35Z | [
"python",
"regex",
"string"
] | Here is my problem: in a variable that is text and contains commas, I try to delete only the commas located between two strings (in fact `[` and `]`). For example using the following string:
```
input = "The sun shines, that's fine [not, for, everyone] and if it rains, it Will Be better."
output = "The sun shines, th... | ```
import re
Variable = "The sun shines, that's fine [not, for, everyone] and if it rains, it Will Be better."
Variable1 = re.sub("\[[^]]*\]", lambda x:x.group(0).replace(',',''), Variable)
```
First you need to find the parts of the string that need to be rewritten (you do this with `re.sub`). Then you rewrite that ... |
how to grab internal index of current loop in python when iter a list? | 11,097,963 | 2 | 2012-06-19T09:16:07Z | 11,098,022 | 7 | 2012-06-19T09:20:39Z | [
"python",
"loops",
"indexing",
"counter"
] | i got a `listx =[1,2,3,4,5,6,7,8,9]`
i want to alter every Nth item of the list. For example i want to modify for every 2 item step, let say i want to modify by +1 .
so i want to get result = `[1+1,2,3+1,4,5+1,6,7+1,8,9+1] =[2,2,4,4,6,6,8,8,9]`
i can do this by using for-loop , by adding counter variable , then check... | You can use the `enumerate` function.
```
newlist = [x + 1 if n % step == 0 else x
for (n, x) in enumerate(oldlist)]
```
The `enumerate` function iterates over a sequence and yields the objects with their indexes. |
Python and Gtk - which GTK version is being used? | 11,098,446 | 3 | 2012-06-19T09:46:16Z | 11,099,204 | 9 | 2012-06-19T10:35:49Z | [
"python",
"gtk",
"pygobject"
] | ```
from gi.repository import Gtk
#print Gtk.GTK_MAJOR_VERSION
win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
```
That is my code, how can I know which version of Gtk is being used.
Thank you! | You can use the following functions to get the version information:
```
Gtk.get_major_version()
Gtk.get_minor_version()
Gtk.get_micro_version()
``` |
Optimal solution to extend a python list by adding the at the beginning of the list instead of tail? | 11,098,836 | 6 | 2012-06-19T10:09:57Z | 11,098,855 | 11 | 2012-06-19T10:11:35Z | [
"python",
"performance",
"list"
] | You have
```
x = ['a', 'b', 'c']
y = [1, 2, 3]
```
And want to insert list `y` at the beginning of `x`:
```
x = [1, 2, 3, a, b, c]
```
What is the optimal solution to do this in Python? | When you want to append on the left, a [`deque`](http://docs.python.org/library/collections.html#collections.deque) is much more efficient than a list. Use the `extendleft` method.
```
>>> from collections import deque
>>> d = deque(['a', 'b', 'c'])
>>> d.extendleft(reversed([1, 2, 3]))
>>> d
deque([1, 2, 3, 'a', 'b',... |
Optimal solution to extend a python list by adding the at the beginning of the list instead of tail? | 11,098,836 | 6 | 2012-06-19T10:09:57Z | 11,100,401 | 8 | 2012-06-19T11:56:38Z | [
"python",
"performance",
"list"
] | You have
```
x = ['a', 'b', 'c']
y = [1, 2, 3]
```
And want to insert list `y` at the beginning of `x`:
```
x = [1, 2, 3, a, b, c]
```
What is the optimal solution to do this in Python? | Depending what you are doing with the result, perhaps you don't want to make a list at all:
```
new_x = itertools.chain(y, x)
```
Now you have an iterator that will produce all the values in y, and then all the values in x. Now you can iterate it:
```
for val in new_x:
blah blah
``` |
How do I use sorl-thumbnail? (django) | 11,099,083 | 3 | 2012-06-19T10:27:17Z | 11,099,124 | 7 | 2012-06-19T10:30:35Z | [
"python",
"django",
"django-models",
"thumbnails",
"sorl-thumbnail"
] | I've been looking at the sorl-thumbnail's documentation, and I still can't figure out how to:
1. upload images to sorl-thumbnail.
2. selectively show images from sorl-thumbnail.
(for example, load a specific image from sorl-thumbnail from a view and show it, with customized size, etc.)
Could you give some specific exa... | You can use sorl.thumbnail using the thumbnail template tags. Here's an example:
```
{% load thumbnail %}
{% thumbnail recipe.image "430x250" as thumb %}
<img src="{{ thumb.url }}" width="{{ thumb.width }}" height="{{ thumb.height }}" alt="{{ recipe.title }}" />
{% endthumbnail %}
```
You don't upload images to... |
Pyramid - Writing unittest for file upload form | 11,102,432 | 2 | 2012-06-19T13:50:22Z | 11,113,387 | 9 | 2012-06-20T05:35:34Z | [
"python",
"unit-testing",
"python-2.7",
"pyramid"
] | I'm strugling with creating unittests for function in charge of uploading pictures recieved from a form on a page.
Main problem is that I can't figure out how to add picture to post parameters of a dummy request and as such pass it to function.
Here is code I'm trying to test.
Thanks
```
@view_config(route_name='pr... | It's really bad practice (and a potential security hole) to actually create a file on your filesystem with the a name supplied by the client (`upload.filename`).
With that out of the way, I see in your code you call `request.params`, `request.POST.get('profile')`, `upload.file` and `upload.filename`. We can mock all o... |
Pyramid: Preventing being forced to restart the pserve | 11,103,718 | 3 | 2012-06-19T14:57:41Z | 11,159,396 | 8 | 2012-06-22T15:33:29Z | [
"python",
"python-2.7",
"pyramid"
] | Although I have set pyramid.reload\_templates to true e.g. "**pyramid.reload\_templates = true**", each time I modify a view, I have to kill the pserve process and restart it in order to see the changes.
How can I get over this and just refresh the page to get the results?
Thank you | Well I think you can add the `--reload` flag when starting the webserver. This will watch for any changes on files and reload the server automatically. i.e `/pserve --reload develoment.ini` |
re.findall which returns a dict of named capturing groups? | 11,103,856 | 31 | 2012-06-19T15:05:11Z | 11,104,110 | 49 | 2012-06-19T15:17:49Z | [
"python",
"regex"
] | Inspired by a now-deleted question; given a regex with named groups, is there a method like `findall` which returns a list of `dict` with the named capturing groups instead of a list of `tuple`?
Given:
```
>>> import re
>>> text = "bob sue jon richard harry"
>>> pat = re.compile('(?P<name>[a-z]+)\s+(?P<name2>[a-z]+)'... | ```
>>> import re
>>> s = "bob sue jon richard harry"
>>> r = re.compile('(?P<name>[a-z]+)\s+(?P<name2>[a-z]+)')
>>> [m.groupdict() for m in r.finditer(s)]
[{'name2': 'sue', 'name': 'bob'}, {'name2': 'richard', 'name': 'jon'}]
``` |
Python Map(Dict) with multiple indexes | 11,105,115 | 10 | 2012-06-19T16:16:03Z | 11,105,215 | 8 | 2012-06-19T16:22:24Z | [
"python",
"dictionary"
] | I am looking for a data structure that holds the same values under two different indexes, where I can access the data by **either *one***.
example:
```
x = mysticalDataStructure()
x.add(1,'karl', dog)
x.add(2,'lisa', cat)
$ x[1].age
2
$ x['karl'].age
2
$ x[1].age = 4
$ x['karl'].age
4
```
Is there anything prerolle... | Is there a particular reason you can't just use a dictionary:
```
x = {}
x[1] = x['karl'] = dog
x[2] = x['lisa'] = cat
```
Then you can access it by either.
If you really don't want to repeat your self you do this:
```
class MysticalDataStructure(dict):
def add(self, key1, key2, value):
return self[key1... |
Python Map(Dict) with multiple indexes | 11,105,115 | 10 | 2012-06-19T16:16:03Z | 11,105,962 | 7 | 2012-06-19T17:12:12Z | [
"python",
"dictionary"
] | I am looking for a data structure that holds the same values under two different indexes, where I can access the data by **either *one***.
example:
```
x = mysticalDataStructure()
x.add(1,'karl', dog)
x.add(2,'lisa', cat)
$ x[1].age
2
$ x['karl'].age
2
$ x[1].age = 4
$ x['karl'].age
4
```
Is there anything prerolle... | ```
class MultiKeyDict(object):
def __init__(self, **kwargs):
self._keys = {}
self._data = {}
for k, v in kwargs.iteritems():
self[k] = v
def __getitem__(self, key):
try:
return self._data[key]
except KeyError:
return self._data[self.... |
How to split a matrix into 4 blocks using numpy? | 11,105,375 | 3 | 2012-06-19T16:33:15Z | 11,105,569 | 8 | 2012-06-19T16:46:57Z | [
"python",
"matrix",
"numpy",
"split",
"strassen"
] | I'm implementing Strassen's Matrix Multiplication using python. In divide step, we divide a larger matrix into smaller sub-matrices. Is there a built-in numpy function to split a matrix? | Not exactly, but using array slicing notation you should be able to do it yourself pretty easily.
```
>>> A = np.linspace(0,24,25).reshape([5,5,])
>>> A
array([[ 0., 1., 2., 3., 4.],
[ 5., 6., 7., 8., 9.],
[ 10., 11., 12., 13., 14.],
[ 15., 16., 17., 18., 19.],
[ 2... |
Error installing and running pywin32 2.7 | 11,106,281 | 14 | 2012-06-19T17:34:42Z | 21,081,675 | 29 | 2014-01-12T23:30:33Z | [
"python",
"winapi",
"installation",
"pywin32"
] | I am coming up with a couple errors after installing:
> pywin32-217.win32-py2.7
I have recently upgraded ArcGIS to 10.1 and it uses Python 2.7 (as opposed to 2.6 that came with ArcGIS 10.0)
When I run the installer on a Windows 7 64 bit, it installs, but throws the following message:
> close failed in file object d... | I had the same problem, but solved it a bit differently. Instead of creating another admin account, I was able to execute the `pywin32-217.win32-py2.7.exe` successfully from a command prompt that I started with *Run as Administrator*. |
Error installing and running pywin32 2.7 | 11,106,281 | 14 | 2012-06-19T17:34:42Z | 21,317,857 | 9 | 2014-01-23T19:43:45Z | [
"python",
"winapi",
"installation",
"pywin32"
] | I am coming up with a couple errors after installing:
> pywin32-217.win32-py2.7
I have recently upgraded ArcGIS to 10.1 and it uses Python 2.7 (as opposed to 2.6 that came with ArcGIS 10.0)
When I run the installer on a Windows 7 64 bit, it installs, but throws the following message:
> close failed in file object d... | An alternate solution is what Mark Hammond suggests [on the pywin32 mailing list](https://mail.python.org/pipermail/python-win32/2012-June/012388.html):
> > This seems to happen if User Access Control (UAC) is disabled - is it
> > disabled for you?
>
> Either way, try running "python scripts\pywin32\_postinstall.py -i... |
URL Safe Base64 in Objective-C | 11,106,393 | 4 | 2012-06-19T17:41:33Z | 11,107,389 | 12 | 2012-06-19T18:47:24Z | [
"python",
"objective-c",
"base64",
"zlib"
] | I've looked at numerous Stack Overflow posts on how to decode Base64 encoded strings in Objective C, but I'm still having issues with it.
Essentially, I'm trying to port a Python script to Objective C. The Python line of code is:
```
zlib.decompress(base64.urlsafe_b64decode(string))
```
When I run "string" through t... | Special thanks to Graham for pointing out the RFC differences, I was able to solve the problem. If anyone in the future encounters this, here's how to solve it:
1. Download the NSData+Base64 code from [here](http://projectswithlove.com/projects/NSData_Base64.zip).
2. In `NSData+Base64.m`, you'll need to change the loo... |
Adding row/column headers to Numpy Matrices | 11,106,536 | 5 | 2012-06-19T17:52:13Z | 11,124,998 | 7 | 2012-06-20T17:31:48Z | [
"python",
"matrix",
"numpy"
] | I have a multidimensional matrix (using numpy) to which I would like to add row/column headers. The data is actually 7x12x12, but I can represent it like this:
```
A=[[[0, 1, 2, 3, 4, 5],
[1, 0, 3, 4, 5, 6],
[2, 3, 0, 5, 6, 7],
[3, 4, 5, 0, 7, 8],
[4, 5, 6, 7, 0, 9],
[5, 6, 7, 8, 9, 0]]... | Numpy will handle n-dimensional array's fine but may of the facilities are limited to 2 dimensional arrays. Not even sure how you want the output file to look.
Many people who would wish for named columns overlook the [recarray()](http://docs.scipy.org/doc/numpy/reference/generated/numpy.recarray.html) capabilities of... |
Adding row/column headers to Numpy Matrices | 11,106,536 | 5 | 2012-06-19T17:52:13Z | 11,146,434 | 10 | 2012-06-21T20:44:02Z | [
"python",
"matrix",
"numpy"
] | I have a multidimensional matrix (using numpy) to which I would like to add row/column headers. The data is actually 7x12x12, but I can represent it like this:
```
A=[[[0, 1, 2, 3, 4, 5],
[1, 0, 3, 4, 5, 6],
[2, 3, 0, 5, 6, 7],
[3, 4, 5, 0, 7, 8],
[4, 5, 6, 7, 0, 9],
[5, 6, 7, 8, 9, 0]]... | With [`pandas.DataFrame.to_csv`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html#pandas.DataFrame.to_csv) you can write the columns and the index to a file:
```
import numpy as np
import pandas as pd
A = np.random.randint(0, 10, size=36).reshape(6, 6)
names = [_ for _ in 'abcdef']
d... |
Adding two pandas dataframes | 11,106,823 | 22 | 2012-06-19T18:11:14Z | 11,112,419 | 36 | 2012-06-20T03:28:12Z | [
"python",
"pandas"
] | I have two dataframes, both indexed by timeseries. I need to add the elements together to form a new dataframe, but only if the index and column are the same. If the item does not exist in one of the dataframes then it should be treated as a zero.
I've tried using `.add` but this sums regardless of index and column. A... | How about `x.add(y, fill_value=0)`?
```
import pandas as pd
df1 = pd.DataFrame([(1,2),(3,4),(5,6)], columns=['a','b'])
Out:
a b
0 1 2
1 3 4
2 5 6
df2 = pd.DataFrame([(100,200),(300,400),(500,600)], columns=['a','b'])
Out:
a b
0 100 200
1 300 400
2 500 600
df_add = df1.add(df2, fill_value=0... |
Alternate Row Colors in Html Tables Using Django | 11,107,544 | 2 | 2012-06-19T18:56:19Z | 11,107,596 | 12 | 2012-06-19T18:59:52Z | [
"python",
"django",
"python-2.7"
] | How does one alternate row colors in a table in django that's generated using a for loop from a list? In asp.net it is possible to do math on the view to easily calculate that, but from what I understand that kind of math is not possible in django, so I'm looking for another way. | I think you are looking for [cycle](https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#cycle).
```
{% for o in some_list %}
<tr class="{% cycle 'red' 'green' %}">
...
</tr>
{% endfor %}
``` |
python ImportError: Cython.Distutils | 11,108,461 | 28 | 2012-06-19T19:59:52Z | 13,798,084 | 12 | 2012-12-10T09:25:42Z | [
"python",
"importerror",
"enthought"
] | I'm having a strange problem while trying to install a python library using its setup.py file. when I run the setup.py file, I get an import error, saying `ImportError: No module named Cython.Distutils`, but I do have such a module, and I can import it on the python command line without any trouble. Why might I be gett... | Your sudo is not getting the right python. This is a known behaviour of sudo in Ubuntu. See this [question](http://stackoverflow.com/questions/257616/sudo-changes-path-why) for more info. You need to make sure that sudo calls the right python, either by using the full path:
```
sudo /usr/local/epd/bin/python setup.py ... |
python ImportError: Cython.Distutils | 11,108,461 | 28 | 2012-06-19T19:59:52Z | 26,687,525 | 31 | 2014-11-01T08:38:09Z | [
"python",
"importerror",
"enthought"
] | I'm having a strange problem while trying to install a python library using its setup.py file. when I run the setup.py file, I get an import error, saying `ImportError: No module named Cython.Distutils`, but I do have such a module, and I can import it on the python command line without any trouble. Why might I be gett... | Install Cython:
```
pip install cython
``` |
Python: Dynamic "from" import | 11,108,628 | 3 | 2012-06-19T20:11:17Z | 11,108,712 | 7 | 2012-06-19T20:17:01Z | [
"python"
] | So i'm trying to turn a bunch of "from x import x" statements, that look like this:
```
from class_foo import class_foo
```
into something dynamic. I'm trying to pass a path to a directory and have it import all of the modules therein.
```
def dynamicImport(dirPath):
filez = os.listdir(dirPath)
for file in f... | You're `exec`ing your import statement in your function's local namespace, so that's where the names are defined. This namespace goes away when the function ends, leaving you with nothing. What you probably want is something like `exec imp_statement in globals()`.
Why not just use [`__import__()`](http://docs.python.o... |
Optimizing Python distance calculation while accounting for periodic boundary conditions | 11,108,869 | 7 | 2012-06-19T20:27:12Z | 11,109,336 | 8 | 2012-06-19T20:58:26Z | [
"python",
"optimization",
"list-comprehension"
] | I have written a Python script to calculate the distance between two points in 3D space while accounting for periodic boundary conditions. The problem is that I need to do this calculation for many, many points and the calculation is quite slow. Here is my function.
```
def PBCdist(coord1,coord2,UC):
dx = coord1[0... | You should write your `distance()` function in a way that you can vectorise the loop over the 5711 points. The following implementation accepts an array of points as either the `x0` or `x1` parameter:
```
def distance(x0, x1, dimensions):
delta = numpy.abs(x0 - x1)
delta = numpy.where(delta > 0.5 * dimensions,... |
Python: How can I read in the characters from a line in a file and convert them to floats and strs, depending on if they are numbers or letters? | 11,109,470 | 4 | 2012-06-19T21:09:15Z | 11,109,523 | 7 | 2012-06-19T21:13:13Z | [
"python",
"input"
] | I have a file that looks like:
```
1 1 C C 1.9873 2.347 3.88776
1 2 C Si 4.887 9.009 1.21
```
I would like to read in the contents of the file, line-by-line. When I only had numbers on the lines I used:
```
for line in readlines(file):
data = map(float, line.split)
```
But this only works when all the elements... | ```
$ cat 1.py
def float_or_str(x):
try:
return float(x)
except ValueError:
return x
line = '1 1 C C 1.9873 2.347 3.88776'
print map(float_or_str, line.split())
$python 1.py
[1.0, 1.0, 'C', 'C', 1.9873, 2.347, 3.88776]
``` |
changing global variable when multiprocessing in python | 11,109,776 | 5 | 2012-06-19T21:33:05Z | 11,109,814 | 13 | 2012-06-19T21:35:28Z | [
"python",
"python-2.7",
"multiprocessing"
] | So what I am trying to do ultimately is read a line, do some calculations with the info in that line, then add the result to some global object, but I can never seem to get it to work. For instance, test is always 0 in the code below. I know this is wrong, and I have tried doing it other ways, but it still isn't workin... | The worker processes spawned by the pool get their own copy of the global variable and update that. They don't share memory unless you set that up explicitly. The easiest solution is to communicate the final value of `test` back to the main process, e.g. via the return value. Something like (**untested**):
```
def pro... |
Weird closure behavior in python | 11,109,838 | 13 | 2012-06-19T21:37:07Z | 11,109,876 | 9 | 2012-06-19T21:41:06Z | [
"python",
"closures"
] | I have a following simple code:
```
def get():
return [lambda: i for i in [1, 2, 3]]
for f in get():
print(f())
```
As expected from my python knowledge, output is 3 - entire list will contain last value of `i`. But how this works internally?
AFAIK, python variables are simply reference to objects, so first... | Closures don't refer to *variables* but rather to *scopes*. Since the last value of `i` in its scope is '3', all three closures return the same. To "lock" the current value of a variable, create a new scope just for it:
```
def get() : return [ (lambda x: lambda: x)(i) for i in [ 1, 2, 3 ] ]
for f in get() : print( f(... |
Weird closure behavior in python | 11,109,838 | 13 | 2012-06-19T21:37:07Z | 11,109,935 | 11 | 2012-06-19T21:45:34Z | [
"python",
"closures"
] | I have a following simple code:
```
def get():
return [lambda: i for i in [1, 2, 3]]
for f in get():
print(f())
```
As expected from my python knowledge, output is 3 - entire list will contain last value of `i`. But how this works internally?
AFAIK, python variables are simply reference to objects, so first... | As @thg435 points out, a lambda will not encapsulate the values at that moment, but rather the scope. There are too small ways you can address this:
lambda default argument "hack"
```
[ lambda v=i: v for i in [ 1, 2, 3 ] ]
```
Or use functools.partial
```
from functools import partial
[ partial(lambda v: v, i) for ... |
Pipe output from shell command to a python script | 11,109,859 | 13 | 2012-06-19T21:39:06Z | 11,109,920 | 7 | 2012-06-19T21:44:28Z | [
"python",
"unix"
] | I want to run a `mysql` command and set the output of that to be a variable in my python script.
Here is the shell command I'm trying to run:
```
$ mysql my_database --html -e "select * from limbs" | ./script.py
```
Here is the python script:
```
#!/usr/bin/env python
import sys
def hello(variable):
print var... | When you pipe the output of one command to a pytho script, it goes to sys.stdin. You can read from sys.stdin just like a file. Example:
```
import sys
print sys.stdin.read()
```
This program literally outputs its input. |
Pipe output from shell command to a python script | 11,109,859 | 13 | 2012-06-19T21:39:06Z | 11,109,926 | 11 | 2012-06-19T21:44:46Z | [
"python",
"unix"
] | I want to run a `mysql` command and set the output of that to be a variable in my python script.
Here is the shell command I'm trying to run:
```
$ mysql my_database --html -e "select * from limbs" | ./script.py
```
Here is the python script:
```
#!/usr/bin/env python
import sys
def hello(variable):
print var... | You need to read from stdin to retrieve the data in the python script e.g.
```
#!/usr/bin/env python
import sys
def hello(variable):
print variable
data = sys.stdin.read()
hello(data)
```
If all you want to do here is grab some data from a mysql database and then manipulate it with Python I would skip piping i... |
Pipe output from shell command to a python script | 11,109,859 | 13 | 2012-06-19T21:39:06Z | 11,111,088 | 11 | 2012-06-19T23:53:21Z | [
"python",
"unix"
] | I want to run a `mysql` command and set the output of that to be a variable in my python script.
Here is the shell command I'm trying to run:
```
$ mysql my_database --html -e "select * from limbs" | ./script.py
```
Here is the python script:
```
#!/usr/bin/env python
import sys
def hello(variable):
print var... | If you want your script to behave like many unix command line tools and accept a pipe or a filename as first argument, you can use the following:
```
#!/usr/bin/env python
import sys
# use stdin if it's full
if not sys.stdin.isatty():
input_stream = sys.stdi... |
Python - How to pass iterables into product()? | 11,110,292 | 2 | 2012-06-19T22:16:31Z | 11,110,319 | 7 | 2012-06-19T22:19:12Z | [
"python",
"product"
] | I was trying to use the product() function in Python. I know product() takes a bunch of iterables and does the Cartesian product of all of them.
Now I put all the iterables in a list. I'm wondering how to pass all the iterables in that list at once? I can't pass in the list to product directly because then product()'l... | ```
l = [[1, 2, 3], ('a', 'b')]
product(*l)
```
This is called [Unpacking argument lists](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists). |
How to set different levels for different python log handlers | 11,111,064 | 21 | 2012-06-19T23:49:30Z | 11,111,212 | 23 | 2012-06-20T00:12:08Z | [
"python",
"logging"
] | I've read a few posts on this but I'm still confused. I have this logging setup:
```
import logging
class MongoHandler(logging.Handler):
def __init__(self):
logging.Handler.__init__(self)
from pymongo import Connection
self.db = Connection('db_server').db_name
def emit(self, record):
... | You can set a different logging level for each logging handler but it seems you will have to set the logger's level to the "lowest". In the example below I set the logger to DEBUG, the stream handler to INFO and the TimedRotatingFileHandler to DEBUG. So the file has DEBUG entries and the stream outputs only INFO. You c... |
Spell out the time | 11,111,417 | 2 | 2012-06-20T00:46:03Z | 11,111,447 | 7 | 2012-06-20T00:49:43Z | [
"java",
"c++",
"python",
"linux",
"perl"
] | Are there any libraries or utilities that will formally spell out the time?
```
Examples:
5:37 -> five thirty-seven
2:00 -> two o'clock
4:05 -> five past four
12:00 -> noon
```
Bonus if it can also spell out the date. | Several. Perl options include [Time::Human](http://p3rl.org/Time%3a%3aHuman) (and the related [DateTime::Format::Human](http://p3rl.org/DateTime%3a%3aFormat%3a%3aHuman)), [Time::Fuzzy](http://p3rl.org/Time%3a%3aFuzzy), and [Time::ProseClock](http://p3rl.org/Time%3a%3aProseClock). |
Python - Read second column from file | 11,111,625 | 5 | 2012-06-20T01:19:15Z | 11,111,647 | 7 | 2012-06-20T01:22:36Z | [
"python",
"for-loop",
"file-io",
"readfile"
] | My input file has two columns. I am trying to print the second column of `inputdata1.txt` within a second for-loop. But my code is not working. Can someone tell me what should I do? | You could do something like this. `Separator` is the character your file uses to separate colums, e.g. tabs or commas.
```
for line in open("inputfile.txt"):
columns = line.split(separator)
if len(columns) >= 2:
print columns[1]
``` |
Python - Read second column from file | 11,111,625 | 5 | 2012-06-20T01:19:15Z | 11,111,651 | 8 | 2012-06-20T01:23:09Z | [
"python",
"for-loop",
"file-io",
"readfile"
] | My input file has two columns. I am trying to print the second column of `inputdata1.txt` within a second for-loop. But my code is not working. Can someone tell me what should I do? | ```
with open('inputdata1.txt') as inf:
for line in inf:
parts = line.split() # split line into parts
if len(parts) > 1: # if at least 2 parts/columns
print parts[1] # print column 2
```
This assumes the columns are separated by whitespace.
Function [split()](http://docs.python.org... |
Python - Best/Cleanest way to define constant lists or dictionarys | 11,111,632 | 18 | 2012-06-20T01:21:02Z | 11,111,655 | 15 | 2012-06-20T01:23:39Z | [
"python",
"c",
"header",
"constants",
"organized"
] | First time user on stack overflow and I'm excited to be here.
INTRO: I recently began the magical adventure into the world of Python programming - I love it. Now everything has gone smoothly in my awkward transition from C, but I'm having trouble creating something which would be synonymous to a HEADER file (.h).
PRO... | Put your constants into their own module:
```
# constants.py
RED = 1
BLUE = 2
GREEN = 3
```
Then import that module and use the constants:
```
import constants
print "RED is", constants.RED
```
The constants can be any value you like, I've shown integers here, but lists and dicts would work just the same. |
Problems with psycopg2 installation/Python path | 11,111,965 | 5 | 2012-06-20T02:14:43Z | 11,113,112 | 10 | 2012-06-20T05:05:19Z | [
"python",
"django",
"virtualenv",
"pythonpath"
] | I created a virtualenv in my django app folder, and there I installed all my python dependencies. My Django project is called theme, so in the theme folder there is a venv folder that contains the python libs.
If I run `python manage.py syncdb` it throws`Error was: No module named postgresql_psycopg2.base`. Here is the... | Try to follow the suggestion from the `django.core.exceptions.ImproperlyConfigured` exception:
use `'django.db.backends.postgresql_psycopg2'` instead of `'postgresql_psycopg2'` in `DATABASES` in your settings |
create a lambda function from a string **properly** | 11,112,046 | 11 | 2012-06-20T02:28:06Z | 11,112,080 | 12 | 2012-06-20T02:33:30Z | [
"python",
"string",
"lambda"
] | Given a string such as
```
"2*(i+j) <= 100"
```
I want to generate the corresponding lambda function,
```
fn = lambda i,j: 2*(i+j) <= 100
```
* I can do this with `eval`, but I am seeking a less evil method.
* I have found
```
import ast
f = ast.Lambda('i,j', '2*(i+j) <= 100')
```
but I haven't figure o... | You're looking for an alternative to `eval`, but why? You're accepting arbitrary code and executing it anyway, so why not use `eval`? The only reason to avoid `eval` is because it's dangerous, but the lambda you end up creating will be just as dangerous.
Also, keep in mind, [you really can't make it safe to do this in... |
How to store a floating point number as text without losing precision? | 11,113,767 | 7 | 2012-06-20T06:13:12Z | 11,113,886 | 7 | 2012-06-20T06:22:34Z | [
"python",
"floating-point"
] | Like the question says. Converting to / from the (truncated) string representations can affect their precision. But storing them in other formats like pickle makes them unreadable (yes, I want this too).
How can I store floating point numbers in text without losing precision? | Store it in binary or a power thereof.
```
>>> (3.4).hex()
'0x1.b333333333333p+1'
>>> float.fromhex('0x1.b333333333333p+1')
3.4
``` |
Pythonic solution to drop N values from an iterator | 11,113,803 | 6 | 2012-06-20T06:15:35Z | 11,113,861 | 7 | 2012-06-20T06:20:40Z | [
"python",
"iterator"
] | Is there a pythonic solution to drop `n` values from an iterator? You can do this by just discarding `n` values as follows:
```
def _drop(it, n):
for _ in xrange(n):
it.next()
```
But this is IMO not as elegant as Python code should be. Is there a better approach I am missing here? | I believe you are looking for the "consume" recipe
<http://docs.python.org/library/itertools.html#recipes>
```
def consume(iterator, n):
"Advance the iterator n-steps ahead. If n is none, consume entirely."
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterator... |
Use Git commands within Python code | 11,113,896 | 5 | 2012-06-20T06:23:18Z | 11,114,028 | 11 | 2012-06-20T06:33:24Z | [
"python",
"git"
] | I have been asked to write a script that pulls the latest code from Git, makes a build, and performs some automated unit tests.
I found that there are two built-in Python modules for interacting with Git that are readily available: `GitPython` and `libgit2`.
What approach/module should I use? | An easier solution would be to use the Python `subprocess` module to call git. In your case, this would pull the latest code and build:
```
import subprocess
subprocess.call(["git", "pull"])
subprocess.call(["make"])
subprocess.call(["make", "test"])
``` |
In-memory storage for flask application | 11,113,903 | 6 | 2012-06-20T06:24:02Z | 11,135,936 | 8 | 2012-06-21T10:09:13Z | [
"python",
"flask"
] | My flask application stores some data in a database.
I want this data to be discarded if my application has been down for some time.
The reason for this is that I want to be sure that I missed no REST call to my application.
The obvious and efficient solution is storing this data in memory but I am open to any solutio... | If you don't need persistence in your application, why don't you use the SQLite backend ([easy in flask](http://flask.pocoo.org/docs/patterns/sqlite3/)) and store the database in memory (using the `:memory:` filename as data base), then on each shutdown your data will be cleaned. |
Installing SciPy and NumPy using pip | 11,114,225 | 115 | 2012-06-20T06:48:00Z | 14,639,949 | 32 | 2013-02-01T04:52:24Z | [
"python",
"numpy",
"scipy",
"pip",
"apt"
] | I'm trying to create required libraries in a package I'm distributing. It requires both the [SciPy](http://en.wikipedia.org/wiki/SciPy) and [NumPy](http://en.wikipedia.org/wiki/NumPy) libraries.
While developing, I installed both using
```
apt-get install scipy
```
which installed SciPy 0.9.0 and NumPy 1.5.1, and it ... | I am assuming Linux experience in my answer; I found that there are three prerequisites to getting `pip install scipy` to proceed nicely.
Go here: [Installing SciPY](http://www.scipy.org/Installing_SciPy/BuildingGeneral)
Follow the instructions to download, build and export the env variable for [BLAS](http://en.wikip... |
Installing SciPy and NumPy using pip | 11,114,225 | 115 | 2012-06-20T06:48:00Z | 28,459,468 | 61 | 2015-02-11T16:32:30Z | [
"python",
"numpy",
"scipy",
"pip",
"apt"
] | I'm trying to create required libraries in a package I'm distributing. It requires both the [SciPy](http://en.wikipedia.org/wiki/SciPy) and [NumPy](http://en.wikipedia.org/wiki/NumPy) libraries.
While developing, I installed both using
```
apt-get install scipy
```
which installed SciPy 0.9.0 and NumPy 1.5.1, and it ... | you need the libblas and liblapack dev packages if you are using Ubuntu.
```
aptitude install libblas-dev liblapack-dev
pip install scipy
``` |
Installing SciPy and NumPy using pip | 11,114,225 | 115 | 2012-06-20T06:48:00Z | 31,840,553 | 219 | 2015-08-05T18:51:21Z | [
"python",
"numpy",
"scipy",
"pip",
"apt"
] | I'm trying to create required libraries in a package I'm distributing. It requires both the [SciPy](http://en.wikipedia.org/wiki/SciPy) and [NumPy](http://en.wikipedia.org/wiki/NumPy) libraries.
While developing, I installed both using
```
apt-get install scipy
```
which installed SciPy 0.9.0 and NumPy 1.5.1, and it ... | This worked for me on Ubuntu 14.04:
```
sudo apt-get install libblas-dev liblapack-dev libatlas-base-dev gfortran
pip install scipy
``` |
How to visualize descriptor matching using opencv module in python | 11,114,349 | 6 | 2012-06-20T06:57:22Z | 14,069,570 | 14 | 2012-12-28T12:27:16Z | [
"python",
"opencv",
"image-processing",
"descriptor"
] | I am trying to use opencv with python. I wrote a descriptor (SIFT, SURF, or ORB) matching code in C++ version of opencv 2.4. I want to convert this code to opencv with python. I found some documents about how to use opencv functions in c++ but many of the opencv function in python I could not find how to use them. Here... | you can visualize the feature matching in Python as following. Note the use of scipy library.
```
# matching features of two images
import cv2
import sys
import scipy as sp
if len(sys.argv) < 3:
print 'usage: %s img1 img2' % sys.argv[0]
sys.exit(1)
img1_path = sys.argv[1]
img2_path = sys.argv[2]
img1 = cv2.... |
How to visualize descriptor matching using opencv module in python | 11,114,349 | 6 | 2012-06-20T06:57:22Z | 26,240,284 | 9 | 2014-10-07T15:59:30Z | [
"python",
"opencv",
"image-processing",
"descriptor"
] | I am trying to use opencv with python. I wrote a descriptor (SIFT, SURF, or ORB) matching code in C++ version of opencv 2.4. I want to convert this code to opencv with python. I found some documents about how to use opencv functions in c++ but many of the opencv function in python I could not find how to use them. Here... | I've also written something myself that just uses the OpenCV Python interface and I didn't use `scipy`. `drawMatches` is part of OpenCV 3.0.0 and isn't part of OpenCV 2, which is what I'm currently using. Even though I'm late to the party, here's my own implementation that mimics `drawMatches` to the best of my ability... |
How do I remove dicts from a list with duplicate fields in python? | 11,114,358 | 5 | 2012-06-20T06:58:12Z | 11,114,394 | 11 | 2012-06-20T07:00:26Z | [
"python",
"list",
"dictionary",
"duplicates"
] | Let's say I have a list of dicts. I define "duplicates" as any two dicts in the list that have the same value for the field "id" (even if the other fields are different). How do I remove these duplicates.
An example list would be something like:
```
[{'name': 'John' , 'id':1}, {'name': 'Mike' , 'id':5},{'name': 'Dan'... | Dump them into another dictionary, then pull them out after.
```
dict((x['id'], x) for x in L).values()
``` |
Check if a file is not open( not used by other process) in Python | 11,114,492 | 22 | 2012-06-20T07:07:37Z | 11,115,521 | 19 | 2012-06-20T08:23:44Z | [
"python"
] | I my application, i have below requests:
1. There has one thread will regularly record some logs in file. The log file will be rollovered in certain interval. for keeping the log files small.
2. There has another thread also will regularly to process these log files. ex: Move the log files to other place, parse the log... | An issue with trying to find out if a file is being used by another process is the possibility of a race condition. You could check a file, decide that it is not in use, then just before you open it another process (or thread) leaps in and grabs it (or even deletes it).
Ok, let's say you decide to live with that possi... |
Creating hidden arguments with Python argparse | 11,114,589 | 48 | 2012-06-20T07:15:27Z | 11,114,654 | 61 | 2012-06-20T07:19:44Z | [
"python",
"argparse"
] | Is it possible to add an Argument to an python [`argparse.ArgumentParser`](http://docs.python.org/library/argparse.html#module-argparse) without it showing up in the usage or help (`script.py --help`)? | Yes, you can set the `help` option to `add_argument` to `argparse.SUPPRESS`. Here's an example from the [argparse documentation](http://docs.python.org/dev/library/argparse.html#help):
```
>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('--foo', help=argparse.SUPPRESS)
>>> parser.print_hel... |
Bash: How refresh shell after installing virtualenvwrapper [Without restarting the shell]? | 11,114,788 | 7 | 2012-06-20T07:29:13Z | 11,131,918 | 14 | 2012-06-21T05:20:22Z | [
"python",
"bash",
"ubuntu",
"fabric",
"apt-get"
] | I am using `python-fabric` to setup my server, which configures the server programatically.
So, I installed `virtualenvwrapper` as :
```
sudo apt-get install virtualenvwrapper
```
That installed - Virtualenvwrapper and adds its initialization scripts to shell startup.
Generally we restart the shell and it gets init... | Solved the problem :
```
source /etc/bash_completion.d/virtualenvwrapper
```
This is where it was storing all its magic which gets included to `.bashrc` automatically. |
Stroke Width Transform (SWT) implementation (Python) | 11,116,199 | 11 | 2012-06-20T09:06:58Z | 11,142,278 | 12 | 2012-06-21T16:08:24Z | [
"python",
"opencv",
"computer-vision",
"ocr",
"simplecv"
] | Can anyone describe how can i implement SWT in python using opencv or simplecv ? | Ok so here goes:
The link that has details on the implementation with the code download link at the bottom: [SWT](https://sites.google.com/site/roboticssaurav/strokewidthnokia)
For the sake of completeness, also mentioning that SWT or Stroke Width Transform was devised by Epshtein and others in 2010 and has turned ou... |
How to get most informative features for scikit-learn classifiers? | 11,116,697 | 36 | 2012-06-20T09:36:19Z | 11,116,960 | 39 | 2012-06-20T09:51:55Z | [
"python",
"machine-learning",
"classification",
"scikit-learn"
] | The classifiers in machine learning packages like liblinear and nltk offer a method `show_most_informative_features()`, which is really helpful for debugging features:
```
viagra = None ok : spam = 4.5 : 1.0
hello = True ok : spam = 4.5 : 1.0
hello = None spam : ok = ... | The classifiers themselves do not record feature names, they just see numeric arrays. However, if you extracted your features using a `Vectorizer`/`CountVectorizer`/`TfidfVectorizer`/`DictVectorizer`, *and* you are using a linear model (e.g. `LinearSVC` or Naive Bayes) then you can apply the same trick that the [docume... |
How to get most informative features for scikit-learn classifiers? | 11,116,697 | 36 | 2012-06-20T09:36:19Z | 11,140,887 | 23 | 2012-06-21T14:55:49Z | [
"python",
"machine-learning",
"classification",
"scikit-learn"
] | The classifiers in machine learning packages like liblinear and nltk offer a method `show_most_informative_features()`, which is really helpful for debugging features:
```
viagra = None ok : spam = 4.5 : 1.0
hello = True ok : spam = 4.5 : 1.0
hello = None spam : ok = ... | With the help of larsmans code I came up with this code for the binary case:
```
def show_most_informative_features(vectorizer, clf, n=20):
feature_names = vectorizer.get_feature_names()
coefs_with_fns = sorted(zip(clf.coef_[0], feature_names))
top = zip(coefs_with_fns[:n], coefs_with_fns[:-(n + 1):-1])
... |
Python: Why is __getattr__ catching AttributeErrors? | 11,116,896 | 13 | 2012-06-20T09:48:45Z | 11,117,254 | 8 | 2012-06-20T10:08:21Z | [
"python",
"exception",
"exception-handling",
"python-3.x",
"python-2.7"
] | I'm struggling with `__getattr__`. I have a complex recursive codebase, where it is important to let exceptions propagate.
```
class A(object):
@property
def a(self):
raise AttributeError('lala')
def __getattr__(self, name):
print('attr: ', name)
return 1
print(A().a)
`... | I just changed the code to
```
class A(object):
@property
def a(self):
print "trying property..."
raise AttributeError('lala')
def __getattr__(self, name):
print('attr: ', name)
return 1
print(A().a)
```
and, as we see, indeed the property is tried first. But as... |
How to tell py.test to skip certain directories? | 11,117,062 | 21 | 2012-06-20T09:57:12Z | 11,119,386 | 8 | 2012-06-20T12:17:39Z | [
"python",
"unit-testing",
"py.test"
] | I tried to use the [`norecursedirs`](http://pytest.org/latest/customize.html#confval-norecursedirs) option inside setup.cfg to tell py.test not to collect tests from certain directories but it seems it does ignore it.
```
[pytest]
norecursedirs= lib/third
```
When I run `py.test` I do see how it does get tests from i... | `norecursedirs` should work. Check whether you have a pytest.ini or other setup.cfg files. How are you invoking `py.test`? |
How to tell py.test to skip certain directories? | 11,117,062 | 21 | 2012-06-20T09:57:12Z | 11,120,513 | 8 | 2012-06-20T13:19:39Z | [
"python",
"unit-testing",
"py.test"
] | I tried to use the [`norecursedirs`](http://pytest.org/latest/customize.html#confval-norecursedirs) option inside setup.cfg to tell py.test not to collect tests from certain directories but it seems it does ignore it.
```
[pytest]
norecursedirs= lib/third
```
When I run `py.test` I do see how it does get tests from i... | I solved the mistery, if a pytest section is found in one of the possible config files (`pytest.ini`, `tox.ini` and `setup.cfg`), pytest will not look for other so be sure you define the py.test options in a single file.
I would suggest on using `setup.cfg`. |
How to tell py.test to skip certain directories? | 11,117,062 | 21 | 2012-06-20T09:57:12Z | 24,625,380 | 7 | 2014-07-08T06:50:36Z | [
"python",
"unit-testing",
"py.test"
] | I tried to use the [`norecursedirs`](http://pytest.org/latest/customize.html#confval-norecursedirs) option inside setup.cfg to tell py.test not to collect tests from certain directories but it seems it does ignore it.
```
[pytest]
norecursedirs= lib/third
```
When I run `py.test` I do see how it does get tests from i... | You can use
```
py.test -k 'not third'
```
that excludes all 'third' directory contents. |
String Joining from Iterable containing Strings and ( NoneType / Undefined ) | 11,119,285 | 6 | 2012-06-20T12:12:02Z | 11,119,332 | 14 | 2012-06-20T12:14:33Z | [
"python"
] | I am looking for a clean way to combine variables into a single string with a predefined separator. The problem is that sometimes some of these variables wont always exist or can be set to None. I cant have the separator string duplicate either. Example of problem:
```
# This works because I have all strings
str('-').... | You can use a comprehension to populate your iterable with a conditional checking that values have a truthy value.
```
your_list = ['productX', 'deployment-package', '1.2.3.4', None, None, None]
'-'.join(item for item in your_list if item)
``` |
bitwise XOR of hex numbers in python | 11,119,632 | 28 | 2012-06-20T12:32:29Z | 11,119,660 | 83 | 2012-06-20T12:34:19Z | [
"python",
"hex",
"bit-manipulation",
"xor"
] | how can we XOR hex numbers in python eg. I want to xor 'ABCD' to '12EF'. answer should be B922.
i used below code but it is returning garbage value
```
def strxor(a, b): # xor two strings of different lengths
if len(a) > len(b):
return "".join(["%s" % (ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])
else... | Whoa. You're really over-complicating it by a very long distance. Try:
```
>>> print hex(0x12ef ^ 0xabcd)
0xb922
```
You seem to be ignoring these handy facts, at least:
* Python has native support for hexadecimal integer literals, with the `0x` prefix.
* "Hexadecimal" is just a presentation detail; the arithmetic i... |
bitwise XOR of hex numbers in python | 11,119,632 | 28 | 2012-06-20T12:32:29Z | 13,647,685 | 8 | 2012-11-30T15:01:46Z | [
"python",
"hex",
"bit-manipulation",
"xor"
] | how can we XOR hex numbers in python eg. I want to xor 'ABCD' to '12EF'. answer should be B922.
i used below code but it is returning garbage value
```
def strxor(a, b): # xor two strings of different lengths
if len(a) > len(b):
return "".join(["%s" % (ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])
else... | If the two hex strings are the same length and you want a hex string output then you might try this.
```
def hexxor(a, b): # xor two hex strings of the same length
return "".join(["%x" % (int(x,16) ^ int(y,16)) for (x, y) in zip(a, b)])
``` |
Classes How I understand them. Correct me if Im wrong please | 11,119,704 | 3 | 2012-06-20T12:36:57Z | 11,119,774 | 9 | 2012-06-20T12:40:37Z | [
"python",
"class"
] | I really hope this is not a question posed by millions of newbies, but my search didn t really give me a satisfying answer.
So my question is fairly simple. Are classes basically a container for functions with its own namespace? What other functions do they have beside providing a separate namespace and holding functi... | 1. More importantly than functions, class instances hold data attributes, allowing you to define new data types beyond what is built into the language; and
2. they support [inheritance](https://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29) and [duck typing](https://en.wikipedia.org/wiki/Duck_typi... |
Classes How I understand them. Correct me if Im wrong please | 11,119,704 | 3 | 2012-06-20T12:36:57Z | 11,119,782 | 8 | 2012-06-20T12:41:01Z | [
"python",
"class"
] | I really hope this is not a question posed by millions of newbies, but my search didn t really give me a satisfying answer.
So my question is fairly simple. Are classes basically a container for functions with its own namespace? What other functions do they have beside providing a separate namespace and holding functi... | In most languages, classes are just pieces of code that describe how to produce an object. That's kinda true in Python too:
```
>>> class ObjectCreator(object):
... pass
...
>>> my_object = ObjectCreator()
>>> print my_object
<__main__.ObjectCreator object at 0x8974f2c>
```
But classes are more than that in P... |
Programming Android apps in jython | 11,120,130 | 43 | 2012-06-20T12:58:57Z | 11,122,066 | 35 | 2012-06-20T14:44:01Z | [
"android",
"python",
"jython"
] | The other day I came across a Python implementation called Jython.
With Jython you can write Java applications with Python and compile them to pure Java.
I was wondering: Android programming is done with Java.
So, is it possible to make Android apps with Jython? | Jython doesn't compile to "pure java", it compiles to *java bytecode* - ie, to `*.class` files. To develop for Android, one further compiles java bytecode to Dalvik bytecode. This means that, yes, Jython *can* let you use Python for developing Android, subject to you getting it to play nice with the Android SDK (I have... |
In Python, how can I calculate correlation and statistical significance between two arrays of data? | 11,121,762 | 9 | 2012-06-20T14:26:17Z | 11,122,288 | 7 | 2012-06-20T14:55:29Z | [
"python",
"numpy",
"statistics",
"scipy",
"correlation"
] | I have sets of data with two equally long arrays of data, or I can make an array of two-item entries, and I would like to calculate the correlation and statistical significance represented by the data (which may be tightly correlated, or may have no statistically significant correlation).
I am programming in Python an... | If you want to calculate the Pearson Correlation Coefficient, then `scipy.stats.pearsonr` is the way to go; although, the significance is only meaningful for larger data sets. This function does not require the data to be manipulated to fall into a specified range. The value for the correlation falls in the interval `[... |
python - find char in string - can I get all indexes? | 11,122,291 | 20 | 2012-06-20T14:55:40Z | 11,122,355 | 47 | 2012-06-20T14:58:50Z | [
"python",
"string"
] | got a simple code:
```
def find(str, ch):
for ltr in str:
if ltr == ch:
return str.index(ltr)
find("ooottat", "o")
```
question is: the function only return the first index. If I change return to print, it will print 0 0 0. Why and any way to get 0 1 2? Thanks!! | This is because `str.index(ch)` will return the index where `ch` occurs the first time. Try:
```
def find(s, ch):
return [i for i, ltr in enumerate(s) if ltr == ch]
```
This will return a list of all indexes you need.
P.S. Hugh's answer shows a generator function (it makes a difference if the list of indexes can... |
python - find char in string - can I get all indexes? | 11,122,291 | 20 | 2012-06-20T14:55:40Z | 11,122,744 | 9 | 2012-06-20T15:19:33Z | [
"python",
"string"
] | got a simple code:
```
def find(str, ch):
for ltr in str:
if ltr == ch:
return str.index(ltr)
find("ooottat", "o")
```
question is: the function only return the first index. If I change return to print, it will print 0 0 0. Why and any way to get 0 1 2? Thanks!! | I would go with Lev, but it's worth pointing out that if you end up with more complex searches that using re.finditer may be worth bearing in mind (but re's often cause more trouble than worth - but sometimes handy to know)
```
test = "ooottat"
[ (i.start(), i.end()) for i in re.finditer('o', test)]
# [(0, 1), (1, 2),... |
How to test print statements? | 11,122,582 | 12 | 2012-06-20T15:10:56Z | 11,122,716 | 12 | 2012-06-20T15:18:29Z | [
"python",
"unit-testing",
"stdout"
] | You want to write `unittest`-cases for a function like that:
```
def test_me(a):
for b in c:
print do_something(a,b)
```
At first I thought about just collecting the outputs of `do_something` in a string and then returning it, to print and test the whole output together. But it's not always convinient bec... | [`print`](http://docs.python.org/reference/simple_stmts.html#print) prints to [`sys.stdout`](http://docs.python.org/library/sys.html#sys.stdout), which you can reassign to your own object if you wish. The only thing your object needs is a `write` function which takes a single string argument.
Since Python 2.6 you may ... |
Redirect Python 'print' output to Logger | 11,124,093 | 8 | 2012-06-20T16:35:31Z | 11,124,247 | 7 | 2012-06-20T16:44:20Z | [
"python",
"logging",
"stdout"
] | I have a Python script that makes use of 'Print' for printing to stdout. I've recently added logging via Python Logger and would like to make it so these print statements go to logger if logging is enabled. I do not want to modify or remove these print statements.
I can log by doing 'log.info("some info msg")'. I want... | You have two options:
1. Open a logfile and replace sys.stdout with it, not a function:
```
log = open("myprog.log", "a")
sys.stdout = log
>>> print("Hello")
>>> # nothing is printed because it goes to the log file instead.
```
2. Replace print with your log function:
```
# If you're using p... |
Automatically import modules when entering the python or ipython interpreter | 11,124,578 | 59 | 2012-06-20T17:04:51Z | 11,124,610 | 28 | 2012-06-20T17:07:08Z | [
"python",
"numpy",
"ipython"
] | I find myself typing `import numpy as np` almost every single time I fire up the python interpreter. How do I set up the python or ipython interpreter so that numpy is automatically imported? | Use the environment variable [PYTHONSTARTUP](http://docs.python.org/using/cmdline.html#envvar-PYTHONSTARTUP). From the official documentation:
> If this is the name of a readable file, the Python commands in that
> file are executed before the first prompt is displayed in interactive
> mode. The file is executed in th... |
Automatically import modules when entering the python or ipython interpreter | 11,124,578 | 59 | 2012-06-20T17:04:51Z | 11,124,846 | 32 | 2012-06-20T17:22:38Z | [
"python",
"numpy",
"ipython"
] | I find myself typing `import numpy as np` almost every single time I fire up the python interpreter. How do I set up the python or ipython interpreter so that numpy is automatically imported? | For ipython, there are two ways to achieve this. Both involve ipython's configuration directory which is located in `~/.ipython`.
1. Create a custom ipython profile.
2. Or you can add a startup file to `~/.ipython/profile_default/startup/`
For simplicity, I'd use option 2. All you have to do is place a `.py` or `.ipy... |
Automatically import modules when entering the python or ipython interpreter | 11,124,578 | 59 | 2012-06-20T17:04:51Z | 11,125,085 | 10 | 2012-06-20T17:37:54Z | [
"python",
"numpy",
"ipython"
] | I find myself typing `import numpy as np` almost every single time I fire up the python interpreter. How do I set up the python or ipython interpreter so that numpy is automatically imported? | I use a ~/.startup.py file like this:
```
# Ned's .startup.py file
print("(.startup.py)")
import datetime, os, pprint, re, sys, time
print("(imported datetime, os, pprint, re, sys, time)")
pp = pprint.pprint
```
Then define PYTHONSTARTUP=~/.startup.py, and Python will use it when starting a shell.
The print stateme... |
Python threading.Timer only repeats once | 11,124,640 | 3 | 2012-06-20T17:09:13Z | 11,124,878 | 9 | 2012-06-20T17:23:59Z | [
"python",
"multithreading"
] | ```
def On_Instrumentation_StartAnimation():
"""
Syntax : On_Instrumentation_StartAnimation()
Purpose : Fired if the animation is started
Parameters : None
"""
print "----------------------------------------------------------------------------------------"
localtime = time.ascti... | From the documentation:
> class threading.Timer
>
> A thread that executes a function after a specified interval has passed.
This means `Threading.Timer` will call a function **after** a specified period of time. And as you noticed, it gets called only once. The solution here will to have the timer set once again at ... |
Creating link to an url of Flask app in jinja2 template | 11,124,940 | 17 | 2012-06-20T17:28:07Z | 11,125,138 | 48 | 2012-06-20T17:41:25Z | [
"python",
"flask",
"jinja2",
"url-for"
] | In my Flask app, I have a view which displays a post
```
@post_blueprint.route('/post/<int:year>/<int:month>/<title>')
def get_post(year,month,title):
# My code
```
To display the last 10 entries, I have following view:
```
@post_blueprint.route('/posts/')
def get_all_posts():
# My code
return render_tem... | I feel like you're asking two questions here but I'll take a shot...
For the posting url you'd do this:
```
<a href="{{ url_for('post_blueprint.get_post', year=year, month=month, title=title)}}">
{{ title }}
</a>
```
To handle static files I'd highly suggest using an asset manager like [Flask-Assets](http://flas... |
Python - Flask - open a webpage in default browser | 11,125,196 | 7 | 2012-06-20T17:45:13Z | 11,126,505 | 13 | 2012-06-20T19:09:51Z | [
"python",
"flask"
] | I am working on a small project in Python. It is divided into two parts.
First part is responsible to crawl the web and extract some infromation and insert them into a database.
Second part is resposible for presenting those information with use of the database.
Both parts share the database. In the second part I am ... | I use similar code on Mac OS X (with Safari, Firefox, and Chrome browsers) all the time, and it runs fine. Guessing you may be running into Flask's auto-reload feature. Set `debug=False` and it will not try to auto-reload.
Other suggestions, based on my experience:
* Consider randomizing the port you use, as quick ed... |
size of NumPy array | 11,125,429 | 20 | 2012-06-20T18:00:29Z | 11,125,452 | 33 | 2012-06-20T18:02:01Z | [
"python",
"arrays",
"matlab",
"numpy",
"size"
] | Is there an equivalent to the MATLAB
```
size()
```
command in Numpy?
In MATLAB,
```
>>> a = zeros(2,5)
0 0 0 0 0
0 0 0 0 0
>>> size(a)
2 5
```
In Python,
```
>>> a = zeros((2,5))
>>>
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
>>> ?????
``` | This is called the "shape" in NumPy, and can be requested via the `.shape` attribute:
```
>>> a = zeros((2, 5))
>>> a.shape
(2, 5)
```
If you prefer a function, you could also use `numpy.shape(a)`. |
How to use glBufferData() in PyOpenGL? | 11,125,827 | 2 | 2012-06-20T18:26:36Z | 11,127,618 | 7 | 2012-06-20T20:24:57Z | [
"python",
"opengl",
"pyopengl",
"vertex-buffer"
] | How do you use glBufferData() in the PyOpenGL python bindings to OpenGL?
When I run the following code
```
import sys
from OpenGL.GL import *
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtOpenGL import *
class SimpleTestWidget(QGLWidget):
def __init__(self):
QGLWidget.__init__(sel... | As a workaround, until lists are supported, pass the vertices as a numpy array:
```
vertices = numpy.array([0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5],
dtype='float32')
```
The glVertexPointer call should be `glVertexPointer(2, GL_FLOAT, 0, None)` |
Django - exception handling | 11,126,461 | 2 | 2012-06-20T19:07:09Z | 11,126,634 | 7 | 2012-06-20T19:18:31Z | [
"python",
"django"
] | I'm having this error page in Django.
```
Exception Type: IndexError
Exception Value: list index out of range
Exception Location: /home/nirmal/try/portfolio/views.py in vimeo_authorize, line 52
```
What I need is I just want to except this error in my views. I tried like this:
```
try:
.........
except IndexE... | That code is correct. You're putting it in the wrong place. |
decoding json string in python | 11,126,902 | 5 | 2012-06-20T19:35:52Z | 11,126,962 | 15 | 2012-06-20T19:39:56Z | [
"python",
"json"
] | I have the following JSON string (from wikipedia <http://en.wikipedia.org/wiki/JSON>)
```
{
"name":"Product",
"properties":
{
"id":
{
"type":"number",
"description":"Product identifier",
"req... | You can load json straight from the file like this:
```
f = open("c:/dir/jsondec.json")
data = json.load(f)
```
Based on your input string, `data` is now a dictionary that contains other dictionaries. You can just navigate up the dictionaries like so:
```
node = data['properties']['stock']['properties']['warehous... |
Python: Compare a list to a integer | 11,127,409 | 4 | 2012-06-20T20:11:02Z | 11,127,446 | 12 | 2012-06-20T20:13:48Z | [
"python",
"hex"
] | Ok, no i dont believe this is a repeat question of the other ones on here. Here is what i am trying to do (I am new to Python and self teaching so bear with me).
I have a set of data that is a length of 3. This set makes up a hex value i.e. 0,9,9f is really just the hex value 99f.
I want to take that data set and com... | Where your list is 3 elements containing '99f' - the following returns 2463
```
int(''.join(your_list), 16)
``` |
Scrapy CrawlSpider: how to access item across different levels of parsing | 11,128,596 | 5 | 2012-06-20T21:38:30Z | 11,136,309 | 8 | 2012-06-21T10:36:53Z | [
"python",
"web-scraping",
"scrapy",
"web-crawler",
"multi-level"
] | I'm crawling a web site (only two levels deep), and I want to scrape information from sites on both levels. The problem I'm running into, is I want to fill out the fields of one item with information from both levels. How do I do this?
I was thinking having a list of items as an instance variable that will be accessib... | From scrapy documentation:
In some cases you may be interested in passing arguments to those callback functions so you can receive the arguments later, in the second callback. You can use the Request.meta attribute for that.
Hereâs an example of how to pass an item using this mechanism, to populate different fields... |
tornado equivalent of delay | 11,128,923 | 13 | 2012-06-20T22:09:21Z | 11,135,204 | 26 | 2012-06-21T09:24:45Z | [
"python",
"tornado"
] | Is there an equivalent command in tornado for delay function without affecting the main process to sleep (thus the callbacks would execute even when the main thread is dealying a new function call) | Try this:
```
import time
from tornado.ioloop import IOLoop
from tornado.web import RequestHandler, asynchronous
from tornado import gen
class MyHandler(RequestHandler):
@asynchronous
@gen.engine
def get(self):
self.write("sleeping .... ")
self.flush()
# Do nothing for 5 sec
... |
tornado equivalent of delay | 11,128,923 | 13 | 2012-06-20T22:09:21Z | 28,467,765 | 11 | 2015-02-12T01:29:54Z | [
"python",
"tornado"
] | Is there an equivalent command in tornado for delay function without affecting the main process to sleep (thus the callbacks would execute even when the main thread is dealying a new function call) | Note that since 4.1 they've added a [`gen.sleep(delay)`](http://www.tornadoweb.org/en/stable/gen.html#tornado.gen.sleep) method.
so
```
yield gen.Task(IOLoop.instance().add_timeout, time.time() + 5)
```
would just become
```
yield gen.sleep(5)
``` |
How do I get rid of 'IOError: 13, 'Permission denied'' on Mac OS X | 11,128,970 | 2 | 2012-06-20T22:14:27Z | 11,129,324 | 7 | 2012-06-20T22:51:10Z | [
"python",
"osx",
"osx-lion",
"permission-denied",
"ioerror"
] | Here is my Code that I'm trying to run on Mac OS X:
```
import getpass #Needed for fetching username
import shutil #Needed for moving Files
import os
var_username = getpass.getuser() #gets username and returns as variable
source_file = r"/Users/%s//Downloads/LogNLock/com.lognlock.loginhook.plist" %(var_username) #the ... | The permissions for the folder you are trying to copy the file to are not open enough for you to perform this operation as the user you are are running the script with. This is not really a Python issue. You need to either give the user write permissions to that folder or you need to run the script as root.
To run the... |
Storing numpy sparse matrix in HDF5 (PyTables) | 11,129,429 | 14 | 2012-06-20T23:06:32Z | 11,130,235 | 17 | 2012-06-21T00:56:23Z | [
"python",
"numpy",
"scipy",
"hdf5",
"pytables"
] | I am having trouble storing a numpy csr\_matrix with PyTables. I'm getting this error:
```
TypeError: objects of type ``csr_matrix`` are not supported in this context, sorry; supported objects are: NumPy array, record or scalar; homogeneous list or tuple, integer, float, complex or string
```
My code:
```
f = tables... | A CSR matrix can be fully reconstructed from its `data`, `indices` and `indptr` attributes. These are just regular numpy arrays, so there should be no problem storing them as 3 separate arrays in pytables, then passing them back to the constructor of `csr_matrix`. See the [scipy docs](http://docs.scipy.org/doc/scipy/re... |
Storing numpy sparse matrix in HDF5 (PyTables) | 11,129,429 | 14 | 2012-06-20T23:06:32Z | 22,589,030 | 19 | 2014-03-23T09:23:46Z | [
"python",
"numpy",
"scipy",
"hdf5",
"pytables"
] | I am having trouble storing a numpy csr\_matrix with PyTables. I'm getting this error:
```
TypeError: objects of type ``csr_matrix`` are not supported in this context, sorry; supported objects are: NumPy array, record or scalar; homogeneous list or tuple, integer, float, complex or string
```
My code:
```
f = tables... | The answer by DaveP is *almost* right... but can cause problems for very sparse matrices: if the last column(s) or row(s) are empty, they are dropped. So to be sure that everything works, the "shape" attribute must be stored too.
This is the code I regularly use:
```
import tables as tb
from numpy import array
from s... |
Python "sys.getsizeof" reports same size after items removed from list/dict? | 11,129,546 | 4 | 2012-06-20T23:18:57Z | 11,129,571 | 11 | 2012-06-20T23:22:34Z | [
"python",
"list",
"memory",
"dictionary"
] | I notice that when using sys.getsizeof() to check the size of list and dictionary, something interesting happens.
i have:
```
a = [1,2,3,4,5]
```
with the size of 56 bytes (and empty list has size of 36, so it makes sense because 20/5 = 4)
however, after I remove all the items in the list (using .remove or del), th... | The list doesn't promise to release memory when you remove elements. Lists are over-allocated, which is how they can have amortized O(1) performance for appending elements.
Details of the time performance of the data structures: <http://wiki.python.org/moin/TimeComplexity> |
Python "sys.getsizeof" reports same size after items removed from list/dict? | 11,129,546 | 4 | 2012-06-20T23:18:57Z | 11,129,602 | 7 | 2012-06-20T23:27:29Z | [
"python",
"list",
"memory",
"dictionary"
] | I notice that when using sys.getsizeof() to check the size of list and dictionary, something interesting happens.
i have:
```
a = [1,2,3,4,5]
```
with the size of 56 bytes (and empty list has size of 36, so it makes sense because 20/5 = 4)
however, after I remove all the items in the list (using .remove or del), th... | Increasing the size of a container can be an expensive operation, since it may require that a lot of things be moved around in memory. So Python almost always allocates more memory than is needed for the current contents of a list, allowing any individual addition to the list to have a very good chance of being perform... |
Is checking for the existence of a key in a dictionary better than catching a KeyError in Python? | 11,129,885 | 3 | 2012-06-21T00:06:00Z | 11,129,889 | 10 | 2012-06-21T00:07:10Z | [
"python",
"hash",
"hashmap",
"hashtable"
] | I have a bit of experience in Python but I'm taking the Udacity computer science course to fill in the gaps of what I've learned and to supplement what I already know. The course went over a hashtable lookup function that returns None for the value of a key if the key isn't in the hashtable. Python's dictionary type th... | The best thing is to use dict.get:
```
val = my_dict.get(key, mydefaultval)
```
If there weren't an awesome method like this, I'd recommend using the exception. Python culture is that exceptions are not forbidden, and often the explicit check will actually be catching exceptions anyway. |
boto issue with IAM role | 11,129,976 | 20 | 2012-06-21T00:20:57Z | 11,130,701 | 56 | 2012-06-21T02:17:28Z | [
"python",
"amazon-s3",
"amazon-web-services",
"boto"
] | I'm trying to use AWS' recently announced "IAM roles for EC2" feature, which lets security credentials automatically get delivered to EC2 instances. (see <http://aws.amazon.com/about-aws/whats-new/2012/06/11/Announcing-IAM-Roles-for-EC2-instances/>).
I've set up an instance with an IAM role as described. I can also ge... | If you are using boto 2.5.1 or later it's actually much easier than this. Boto will automatically find the credentials in the instance metadata for you and use them as long as no other credentials are found in environment variables or in a boto config file. So, you should be able to simply do this on the EC2 instance:
... |
line-by-line file processing, for-loop vs with | 11,130,312 | 6 | 2012-06-21T01:08:36Z | 11,130,804 | 10 | 2012-06-21T02:32:06Z | [
"python",
"file-io",
"for-loop",
"with-statement"
] | I am trying to understand the trade offs/differences between these to
ways of opening files for line-by-line processing
```
with open('data.txt') as inf:
for line in inf:
#etc
```
vs
```
for line in open('data.txt'):
# etc
```
I understand that using `with` ensures the file is closed when the
"with-bl... | The problem with this
```
for line in open('data.txt'):
# etc
```
Is that you don't keep an explicit reference to the open file, so how do you close it?
The lazy way is wait for the garbage collector to clean it up, but that may mean that the resources aren't freed in a timely manner.
So you can say
```
inf = op... |
Testing string content on non-whitespace | 11,130,488 | 4 | 2012-06-21T01:40:36Z | 11,130,496 | 7 | 2012-06-21T01:42:02Z | [
"python",
"whitespace"
] | I want to test if a sentence contains anything else than white-space characters. This is what I use currently:
```
if len(teststring.split()) > 0:
# contains something else than white space
else:
# only white space
```
Is this good enough? Are there any better ways of doing it? | I would use the [strip()](http://docs.python.org/library/stdtypes.html?highlight=strip#str.strip) function for this purpose.
```
if teststring.strip():
# non blank line
else:
# blank line
``` |
Testing string content on non-whitespace | 11,130,488 | 4 | 2012-06-21T01:40:36Z | 11,130,506 | 12 | 2012-06-21T01:43:58Z | [
"python",
"whitespace"
] | I want to test if a sentence contains anything else than white-space characters. This is what I use currently:
```
if len(teststring.split()) > 0:
# contains something else than white space
else:
# only white space
```
Is this good enough? Are there any better ways of doing it? | Strings have a method called [`str.isspace`](http://docs.python.org/library/stdtypes.html#str.isspace) which, according to the docs:
> Return[s] true if there are only whitespace characters in the string and there is at least one character, false otherwise.
So, that means:
```
if teststring.isspace():
# contains... |
String formatting [str.format()] with a dictionary key which is a str() of a number | 11,130,790 | 8 | 2012-06-21T02:30:14Z | 11,130,837 | 9 | 2012-06-21T02:38:05Z | [
"python-2.7",
"python"
] | Python neophyte here. I was wondering if someone could help with the `KeyError` I am getting when using a dictionary for string interpolation in [`str.format`](http://docs.python.org/library/stdtypes.html#str.format).
```
dictionary = {'key1': 'val1', '1': 'val2'}
string1 = 'Interpolating {0[key1]}'.format(dictionary... | No. According to [the documentation](http://docs.python.org/library/string.html#formatstrings):
> Because arg\_name is not quote-delimited, it is not possible to specify arbitrary dictionary keys (e.g., the strings '10' or ':-]') within a format string.
So you can't use strings consisting of numbers as dictionary key... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.