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
Counting bigrams (pair of two words) in a file using python
12,488,722
8
2012-09-19T04:44:40Z
12,488,794
23
2012-09-19T04:54:53Z
[ "python", "regex" ]
I want to count the number of occurrences of all bigrams (pair of adjacent words) in a file using python. Here, I am dealing with very large files, so I am looking for an efficient way. I tried using count method with regex "\w+\s\w+" on file contents, but it did not prove to be efficient. e.g. Let's say I want to cou...
Some `itertools` magic: ``` >>> import re >>> from itertools import islice, izip >>> words = re.findall("\w+", "the quick person did not realize his speed and the quick person bumped") >>> print Counter(izip(words, islice(words, 1, None))) ``` Output: ``` Counter({('the', 'quick'): 2, ('quick', 'person'): 2, ('p...
How can I save this matplotlib figure such that the x-axis labels are not cropped out?
12,490,657
4
2012-09-19T08:00:10Z
12,491,287
9
2012-09-19T08:49:25Z
[ "python", "matplotlib", "pandas" ]
I am running the following snippet of code in the ipython notebook, using the `pandas` data analysis library along with `matplotlib.pyplot`. ``` titles = {'gradStat_p3': "P3: Gradiometers", 'magStat_p3': "P3: Magnetometers", 'gradStat_mmn': "MMN: Gradiometers", 'magStat_mmn': "MMN: Magnetometers"} scale...
You can use fig.tight\_layout(). ``` fig, ax = subplots(1,1,1) ax.plot(np.random.randn(5)) ax.set_xticklabels(['this is a very long label', 'b', 'c', 'd', 'e'], rotation=90) fig.tight_layout() fig.savefig('test.pdf') ```
python distutils not include the SWIG generated module
12,491,328
15
2012-09-19T08:52:23Z
21,236,111
8
2014-01-20T14:08:09Z
[ "c++", "python", "swig", "rpm", "distutils" ]
I am using distutils to create an rpm from my project. I have this directory tree: ``` project/ my_module/ data/file.dat my_module1.py my_module2.py src/ header1.h header2.h ext_module1.cpp ext_module2.cp...
The problem is that `build_py` (which copies python sources to the build directory) comes before `build_ext`, which runs SWIG. You can easily subclass the build command and swap around the order, so `build_ext` produces `module1.py` before `build_py` tries to copy it. ``` from distutils.command.build import build cl...
Splitting a string into 2-letter segments
12,491,537
5
2012-09-19T09:04:00Z
12,491,575
13
2012-09-19T09:06:38Z
[ "python", "string", "python-3.x", "iterator" ]
I have a string, which I need to split into 2-letter pieces. For example, `'ABCDXY'` should become `['AB', 'CD', 'XY']`. The behavior in the case of odd number of characters may be entirely arbitrary (I'll check the length in advance). Is there any way to do this without an ugly loop?
``` >>> [s[i:i + 2] for i in range(0, len(s), 2)] ['AB', 'CD', 'XY'] ```
Splitting a string into 2-letter segments
12,491,537
5
2012-09-19T09:04:00Z
12,491,676
15
2012-09-19T09:11:41Z
[ "python", "string", "python-3.x", "iterator" ]
I have a string, which I need to split into 2-letter pieces. For example, `'ABCDXY'` should become `['AB', 'CD', 'XY']`. The behavior in the case of odd number of characters may be entirely arbitrary (I'll check the length in advance). Is there any way to do this without an ugly loop?
Using regular expressions! ``` >>> import re >>> s = "ABCDXYv" >>> re.findall(r'.{1,2}',s,re.DOTALL) ['AB', 'CD', 'XY', 'v'] ``` --- I know it has been a while, but I came back to this and was curious about which method was better; mine: `r'.{1,2}'` or Jon's `r'..?'`. On the surface, Jon's looks much nicer, and I th...
Python sum of ASCII values of all characters in a string
12,492,137
5
2012-09-19T09:39:11Z
12,492,343
16
2012-09-19T09:51:00Z
[ "python", "string", "python-2.7", "ascii" ]
I am searching a more efficient way to sum-up the [ASCII](http://en.wikipedia.org/wiki/ASCII) values of all characters in a given string, using only standard python (2.7 is preferable). Currently I have: ``` print sum(ord(ch) for ch in text) ``` **I want to emphasize that my main focus and aspect of this question is...
You can use an intermediate `bytearray` to speed things up: ``` >>> sum(bytearray("abcdefgh")) 804 ``` This is not 17 times faster than the generator—it involves the creation of an intermediate `bytearray` and `sum` still has to iterate over Python integer objects—but on my machine it does speed up summing an 8-c...
Decorators and class method
12,493,074
18
2012-09-19T10:41:28Z
12,493,278
14
2012-09-19T10:52:29Z
[ "python", "class", "methods", "decorator" ]
I am having trouble understanding why the following happens. I am having a decorator which does nothing except it checks whether a function is a method. I thought I have understood what method in Python is, but obviously, this is not the case: ``` import inspect def deco(f): def g(*args): print inspect.is...
Methods are functions that are associated with a class. Methods are only created when you retrieve them from an already defined class; a method is a wrapper around a function, with a reference to the class as well (and optionally a reference to the instance). What happens in the first case is: Python compiles your cla...
python syntax error with list filtering
12,493,193
2
2012-09-19T10:47:03Z
12,493,225
8
2012-09-19T10:49:15Z
[ "python" ]
I'm trying to filter an item from a list, and I'm getting a syntax error: **SyntaxError: invalid syntax** The code: ``` a['name'] = 'Dan' b['name'] = 'Joe' ppl = [a,b] inputName = raw_input('Enter name:').strip() person = [p in ppl if p['name']==inputName].pop() ``` any idea?
`[item for item in array]` not `[item in array]`
Equivalent of the Scala IDE worksheet in other languages?
12,495,318
9
2012-09-19T13:04:02Z
12,495,693
10
2012-09-19T13:24:22Z
[ "java", "python", "ruby", "ide" ]
> A worksheet is a Scala file that is evaluated on save, and the result of each expression is shown in a column to the right of your program. Worksheets are like a REPL session on steroids, and enjoy 1st class editor support: completion, hyperlinking, interactive errors-as-you-type, auto-format, etc. (source <https://g...
This is not really a language feature, more an IDE feature. It looks like a pretty straightforward clone of the `Transcript` window which has been a standard part of Smalltalk IDEs since at the least the 1980s. *One* of those Smalltalk IDEs is IBM VisualAge for Smalltalk (where it was called *Scrapbook*), which later...
Sorting the catalog results by multiple fields
12,495,813
4
2012-09-19T13:31:19Z
12,495,894
7
2012-09-19T13:35:26Z
[ "python", "plone" ]
I need to sort the catalog results by multiple fields. In my case, first sort by year, then by month. The year and month field are included in my custom content type (`item_publication_year` and `item_publication_month` respectively). However, I'm not getting the results that I want. The year and month are not ordere...
A better bet is to use the `key` parameter for sorting: ``` results.sort(key=lambda b: (b.item_publication_year, b.item_publication_month)) ``` You can also use the [`sorted()` built-in function](http://docs.python.org/library/functions.html#sorted) instead of using `list()`; it'll return a sorted list for you, it's ...
How can I override a constant in an imported Python module?
12,496,089
6
2012-09-19T13:45:55Z
12,496,239
9
2012-09-19T13:52:58Z
[ "python", "module", "python-import" ]
In my application I am using module within the package `example` called `examplemod`. **My app:** ``` from example import examplemod examplemod.do_stuff() ``` It imports another module within `example` like so. **examplemod.py:** ``` from example import config # uses config # then does stuff ``` `config` uses a c...
Yes, but it'll only work as expected with fully qualified access paths to modules: ``` import example example.examplemod.config.CONSTANT = "Better value" example.examplemod.do_stuff() ```
Difference accessing element(s) of tuple and list
12,496,435
3
2012-09-19T14:03:49Z
12,496,458
14
2012-09-19T14:05:03Z
[ "python", "list", "tuples" ]
Why is there this difference accessing the element(s) of `t` when making it a `tuple`? ``` >>> t = [('ID','int')] >>> for r in t: print r ('ID', 'int') t = (('ID','int')) >>> for r in t: print r ID int ``` I'd expect this to be exactly the same as the first example! Whereas populating the tuple with more than o...
`(('a', 'b'))` is the same as `('a', 'b')`. You actually want `(('a', 'b'),)` This is documented here: > [**5.13. Expression lists**](http://docs.python.org/reference/expressions.html#grammar-token-expression_list) > > `expression_list ::= expression ( "," expression )* [","]` > > An expression list containing at le...
Python evaluates 0 as False
12,497,199
2
2012-09-19T14:48:35Z
12,497,224
8
2012-09-19T14:49:49Z
[ "python", "boolean" ]
In the Python console: ``` >>> a = 0 >>> if a: ... print "L" ... >>> a = 1 >>> if a: ... print "L" ... L >>> a = 2 >>> if a: ... print "L" ... L ``` Why does this happen?
0 is a falsy value in python Falsy values: [from (2.7) documentation:](http://docs.python.org/library/stdtypes.html#truth-value-testing) > zero of any numeric type, for example, 0, 0L, 0.0, 0j.
Python evaluates 0 as False
12,497,199
2
2012-09-19T14:48:35Z
12,497,466
8
2012-09-19T15:04:52Z
[ "python", "boolean" ]
In the Python console: ``` >>> a = 0 >>> if a: ... print "L" ... >>> a = 1 >>> if a: ... print "L" ... L >>> a = 2 >>> if a: ... print "L" ... L ``` Why does this happen?
In Python, `bool` is a subclass of `int`, and `False` has the value `0`; even if values weren't implicitly cast to `bool` in an `if` statement (which they are), `False == 0` is true.
python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B
12,497,402
31
2012-09-19T15:01:32Z
13,059,751
52
2012-10-25T00:10:02Z
[ "python", "duplicates", "pandas" ]
I have a dataframe with repeat values in column A. I want to drop duplicates, keeping the row with the highest value in column B. So this: ``` A B 1 10 1 20 2 30 2 40 3 10 ``` Should turn into this: ``` A B 1 20 2 40 3 10 ``` Wes has added some nice functionality to drop duplicates: <http://wesmckinney.com/blog/?p...
This takes the last. Not the maximum though: ``` In [10]: df.drop_duplicates(cols='A', take_last=True) Out[10]: A B 1 1 20 3 2 40 4 3 10 ``` You can do also something like: ``` In [12]: df.groupby('A', group_keys=False).apply(lambda x: x.ix[x.B.idxmax()]) Out[12]: A B A 1 1 20 2 2 40 3 ...
Dynamically building a Boolean expression
12,497,917
6
2012-09-19T15:28:35Z
12,497,972
9
2012-09-19T15:32:07Z
[ "python", "boolean-expression" ]
I'm writing some code that increments the number at the end of a filename until it's no longer overwriting an existing file. I'm creating several files, all with the same base filename but different extensions, none of which I want to overwrite. Naive version: ``` prefix = 'hello0' while os.path.exists(prefix + '.abc...
You might want to use the `any()` built-in with a generator: ``` while any(os.path.exists(prefix + extension) for extension in extensions): # then increment prefix and try again, as in your example code ``` This computes the `True` or `False` that you need with a simpler syntax. In general, if I *ever* feel the...
two level sorting of a list of dictionaries in python
12,498,134
2
2012-09-19T15:40:49Z
12,498,161
8
2012-09-19T15:42:24Z
[ "python", "sorting" ]
I have a list of dictionaries as follows: ``` {"id": 1, "score": some_score.. othe values} {"id": 1, "score": some_differetscore.. othe values} {"id": 22, "score": some_score.. othe values} {"id": 3, "score": some_score.. othe values} ``` What I am hoping to get is to iterate thru this list in such a way that i...
Try this: ``` sorted(mylist, key=lambda d: (d["id"], -d["score"])) ```
Install MySQL-python in virtualenv on Windows 7
12,498,317
7
2012-09-19T15:50:46Z
15,209,295
18
2013-03-04T19:17:40Z
[ "python", "python-2.7", "virtualenv", "pip", "mysql-python" ]
I'm trying to install MySQL-python in my virtualenv (Windows 7 32b + Python 2.7.3), but unfortunately after command: ``` pip install MySQL-python ``` I get error message: ``` Install packages failed: Error occurred when installing package MySQL-python. The following command was executed: packaging_tool.py install...
Did you try using : ``` easy_install MySQL-python ``` It works for me in Windows 7 a long with Virtualenv. I had the same problem with pip.
Install MySQL-python in virtualenv on Windows 7
12,498,317
7
2012-09-19T15:50:46Z
20,092,578
11
2013-11-20T09:54:50Z
[ "python", "python-2.7", "virtualenv", "pip", "mysql-python" ]
I'm trying to install MySQL-python in my virtualenv (Windows 7 32b + Python 2.7.3), but unfortunately after command: ``` pip install MySQL-python ``` I get error message: ``` Install packages failed: Error occurred when installing package MySQL-python. The following command was executed: packaging_tool.py install...
If you can install mysql-python globally (in C:/python27) from <http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python> then you can copy paste the following files from "C:/python/lib/site-packages" to your virtual environment "/lib/site-packages" 1. MySQL\_python-1.2.4-py2.7.egg-info(folder) 2. MySQLdb(folder) 3. \...
Can I set a header with python's SimpleHTTPServer?
12,499,171
33
2012-09-19T16:42:39Z
12,499,670
8
2012-09-19T17:15:00Z
[ "python", "cross-domain", "simplehttpserver" ]
I'm using `SimpleHTTPServer` to test some webpages I'm working on. It works great, however I need to do some cross-domain requests. That requires setting a `Access-Control-Allow-Origin` header with the domains the page is allowed to access. Is there an easy way to set a header with SimpleHTTPServer and serve the origi...
I'd say there's no simple way of doing it, where simple means *"just add 1-2 lines that will write the additional header and keep the existing functionality"*. So, the best solution would be to subclass the `SimpleHTTPRequestHandler` class and re-implement the functionality, with the addition of the new header. The pr...
Can I set a header with python's SimpleHTTPServer?
12,499,171
33
2012-09-19T16:42:39Z
13,354,482
37
2012-11-13T01:42:37Z
[ "python", "cross-domain", "simplehttpserver" ]
I'm using `SimpleHTTPServer` to test some webpages I'm working on. It works great, however I need to do some cross-domain requests. That requires setting a `Access-Control-Allow-Origin` header with the domains the page is allowed to access. Is there an easy way to set a header with SimpleHTTPServer and serve the origi...
This is a bit of a hack because it changes `end_headers()` behavior, but I think it's slightly better than copying and pasting the entire `SimpleHTTPServer.py` file. My approach overrides `end_headers()` in a subclass and in it calls `send_my_headers()` followed by calling the superclass's `end_headers()`. It's not 1...
ctypes how to pass string from python to c++ function, and how to return string from c++ function to python
12,500,069
3
2012-09-19T17:41:24Z
12,500,326
11
2012-09-19T18:00:13Z
[ "c++", "python", "string", "ctypes" ]
I want to call a c++ function from python, this c++ function takes char\* as parameter, and return string. Below is my code. wrapper.cpp ``` #include <Python.h> #include <string> #include <iostream> using namespace std; extern "C" string return_string(char* name){ cout<<strlen(name)<<endl; cout<<name<<endl;...
This has nothing to do with ctypes; your C++ code is invalid in itself. You can't define an `extern "C"` function that returns a `string`. In a quick test with a C++ program that uses the same library, it also prints garbage. I also wrote a C program that defines something called `string` with the same layout as `std...
Passing multple files with asterisk to python shell in Windows
12,501,761
7
2012-09-19T19:43:50Z
12,501,850
9
2012-09-19T19:49:54Z
[ "python", "command-line", "arguments" ]
I'm going through Google's Python exercises and I need to be able to do this from the command line: ``` python babynames.py --summaryfile baby*.html ``` Where `python` is the Python shell, `babynames.py` is the Python program, `--summaryfile` is an argument to be interpreted by my `babynames` program, and `baby*.html...
Windows' command interpreter does not expand wildcards as UNIX shells do before passing them to the executed program or script. ``` python.exe -c "import sys; print sys.argv[1:]" *.txt ``` Result: ``` ['*.txt'] ``` Solution: Use the `glob` module. ``` from glob import glob from sys import argv for filename in glo...
Randomly select x number of items from class list in python
12,501,956
5
2012-09-19T19:57:14Z
12,502,001
9
2012-09-19T20:01:11Z
[ "python", "list", "class", "random", "jython" ]
In jython, I have a class of objects defined like this: ``` class Item: def __init__(self, pid, aisle, bay, hits, qtyPerOrder): self.pid = pid self.aisle = int(aisle) self.bay = bay self.hits = int(hits) self.qtyPerOrder = int(qtyPerOrder) ``` I have created a class list called "list" of the ite...
You can use the [`random` module](http://www.jython.org/docs/library/random.html) to both pick a number between 3 and 20, and to take a sample of lines: ``` import random sample_size = random.randint(3, 20) sample = random.sample(yourlist, sample_size) for item in sample: print '%s, %d, %s, %d' % (item.pid, item...
Python/numpy floating-point text precision
12,502,122
2
2012-09-19T20:08:59Z
12,502,750
7
2012-09-19T20:54:23Z
[ "python", "numpy", "floating-point", "precision" ]
Let's say I have some 32-bit and 64-bit floating point values: ``` >>> import numpy as np >>> v32 = np.array([5, 0.1, 2.4, 4.555555555555555, 12345678.92345678635], dtype=np.float32) >>> v64 = np.array([5, 0.1, 2.4, 4.555555555555555, 12345678.92345678635], dtype=np.float64) ```...
Python 2.7 and later already have a smart `repr` implementation for floats that prints 0.1 as `0.1`. The brief output is chosen in preference to other candidates such as `0.10000000000000001` because it is the shortest representation of *that particular number* that roundtrips to the exact same floating-point value whe...
Access Multiselect Form Field in Flask
12,502,646
8
2012-09-19T20:46:15Z
12,502,681
26
2012-09-19T20:49:13Z
[ "python", "flask" ]
I have a multiselect in html file like this: ``` <select multiple id="mymultiselect" name="mymultiselect"> <option value="1">this</option> <option value="2">that</option> <option value="3">other thing</option> </select> ``` When I access the mymultiselect field in flask/...
You want to use the [`getlist()` function](http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.MultiDict.getlist) to get a list of values: ``` multiselect = request.form.getlist('mymultiselect') ``` You do *not* need to add `[]` to the name to make this work; in fact, the `[]` will not help, don't ...
Making a video with opencv and ffmpeg. How to find the right color format?
12,503,368
10
2012-09-19T21:44:55Z
12,573,365
13
2012-09-24T21:43:06Z
[ "python", "opencv", "image-processing", "ffmpeg" ]
I have a webcam video recorder program built with python, opencv and ffmpeg It works ok except that the color of the video is more blue than the reality. The problem seems to come from color format of images. It seems that OpenCv is giving BGR images and ffmpeg+libx264 is expecting YUV420p. I've read that YUV420p cor...
You are right, the default pixel format of OpenCV is **BGR**. The equivalent format on the ffmpeg side would be **BGR24**, so you don't need to convert it to YUV420p if you don't want to. [This post](http://stackoverflow.com/a/5839058/176769) shows how to use a python application to capture frames from the webcam and...
How to Reverse Hebrew String in Python?
12,504,197
4
2012-09-19T23:19:38Z
12,504,219
7
2012-09-19T23:22:49Z
[ "python" ]
I'm trying to reverse Hebrew string in Python: ``` line = 'אבגד' reversed = line[::-1] print reversed ``` but I get: ``` UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 0: ordinal not in range(128) ``` Care to explain what I'm doing wrong? EDIT: The answers are great, thanks! I'm also tryi...
Adding `u` in front of the hebrew string works for me: ``` In [1]: line = u'אבגד' In [2]: reversed = line[::-1] In [2]: print reversed דגבא ``` --- To your second question, you can use: ``` import codecs w1 = codecs.open("~/fileName", "r", "utf-8") w1.write(reversed) ``` To write unicode string to file ...
How to handle DST and TZ in recurring events?
12,504,247
9
2012-09-19T23:25:38Z
12,527,753
9
2012-09-21T09:24:51Z
[ "python", "datetime", "pytz", "rrule", "python-dateutil" ]
Does dateutil rrule support DST and TZ? Need something similar to iCalendar RRULE. If not - how to tackle this problem (scheduling recurring events & DST offset change) Imports ``` >>> from django.utils import timezone >>> import pytz >>> from datetime import timedelta >>> from dateutil import rrule >>> now = timezo...
@asdf: I can't add code to comments so I need to post this as an answer: I am afraid that with your solution I will always loose DST info, therefore half of the year recurrences would be 1 hour off time. Basing on your answer I found out that this might be the correct solution: ``` >>> from datetime import datetime ...
Adding pandas Series with different indices without getting NaNs
12,504,493
9
2012-09-20T00:02:13Z
12,504,527
18
2012-09-20T00:09:18Z
[ "python", "pandas" ]
I'm trying to do what I think is a straight froward operation in pandas but I can't seem to make it work. I have two pandas Series with different numbers of indices, I would like to add values together if they share an index, otherwise I would just like to pass the values that don't have corresponding indices along. ...
You could use `fill_value`: ``` >>> import pandas as pd >>> Sr1 = pd.Series([1,2,3,4], index = ['A', 'B', 'C', 'D']) >>> Sr2 = pd.Series([5,6], index = ['A', 'C']) >>> Sr1+Sr2 A 6 B NaN C 9 D NaN >>> Sr1.add(Sr2, fill_value=0) A 6 B 2 C 9 D 4 ```
how to see Heroku logging and runtime error output in python
12,504,588
5
2012-09-20T00:17:35Z
12,877,333
11
2012-10-13T21:51:57Z
[ "python", "web-applications", "heroku" ]
I'm working on a web app in Python with Heroku and I can't figure out how to effectively test debug it. I tried using print(...) and sys.stdout.write(...) but I never see any output when I run locally with 'foreman start' or when I deploy to the cloud and run 'heroku logs' to see cloud logs. Furthermore, I can't figure...
Adding `sys.stdout.flush()` after print statements solved this problem for me. In my case, the problem seemed to be that stdout is buffered whereas stderr is not. If you're not even seeing exceptions via `foreman start`, make sure you're actually hitting your server at the right IP/PORT. You should see HTTP access en...
how to see Heroku logging and runtime error output in python
12,504,588
5
2012-09-20T00:17:35Z
21,396,876
7
2014-01-28T04:33:19Z
[ "python", "web-applications", "heroku" ]
I'm working on a web app in Python with Heroku and I can't figure out how to effectively test debug it. I tried using print(...) and sys.stdout.write(...) but I never see any output when I run locally with 'foreman start' or when I deploy to the cloud and run 'heroku logs' to see cloud logs. Furthermore, I can't figure...
If you are using Foreman to run a Python project, and you're having trouble seeing stdout/stderr, here are some solutions for you. If you are using a Procfile to invoke the python CLI directly, then you can use the '-u' option to avoid stdout buffering: ``` python -u script.py ``` If you are using a Procfile to manag...
Behavior of range in python and arange in numpy
12,504,632
2
2012-09-20T00:23:50Z
12,504,653
7
2012-09-20T00:26:59Z
[ "python", "numpy", "range" ]
Can someone please explain the '-5' below. I'm somewhat new to numpy, but this seems bizarre ``` In [112]: an_int=9 In [113]: an_int/2 Out[113]: 4 In [114]: range(-an_int/2,an_int/2) Out[114]: [-5, -4, -3, -2, -1, 0, 1, 2, 3] In [115]: arange(-an_int/2,an_int/2) Out[115]: array([-5, -4, -3, -2, -1, 0, 1, 2, 3])...
The problem isn't numpy. The "problem" is that integer division in python floors the result as opposed to truncating toward 0 (like the C language) -- e.g. `-9/2` *which is parsed as `(-9)/2`* (or `(-9)//2` if you're using python3.x) evaluates to `-5`. The builtin `int` function on the other hand does truncate toward z...
Save session in IPython like in MATLAB?
12,504,951
17
2012-09-20T01:20:19Z
12,505,031
11
2012-09-20T01:34:06Z
[ "python", "ipython", "pandas" ]
It would be useful to save the session variables which could be loaded easily into memory at a later stage.
``` In [23]: %logstart /tmp/session.log Activating auto-logging. Current session state plus future input saved. Filename : /tmp/session.log Mode : backup Output logging : False Raw input log : False Timestamping : False State : active In [24]: x = 1 In [25]: %logstop In [26]: quit() Do yo...
Get last "column" after .str.split() operation on column in pandas DataFrame
12,504,976
20
2012-09-20T01:24:57Z
12,505,089
23
2012-09-20T01:43:43Z
[ "python", "string", "pandas", "split" ]
I have a column in a pandas DataFrame that I would like to split on a single space. The splitting is simple enough with `DataFrame.str.split(' ')`, but I can't make a new column from the last entry. When I `.str.split()` the column I get a list of arrays and I don't know how to manipulate this to get a new column for m...
You could use the `tolist` method as an intermediary: ``` In [99]: import pandas as pd In [100]: d1 = pd.DataFrame({'ticker' : ['spx 5/25/2001 p500', 'spx 5/25/2001 p600', 'spx 5/25/2001 p700']}) In [101]: d1.ticker.str.split().tolist() Out[101]: [['spx', '5/25/2001', 'p500'], ['spx', '5/25/2001', 'p600'], ['spx'...
Get last "column" after .str.split() operation on column in pandas DataFrame
12,504,976
20
2012-09-20T01:24:57Z
13,053,267
26
2012-10-24T16:13:48Z
[ "python", "string", "pandas", "split" ]
I have a column in a pandas DataFrame that I would like to split on a single space. The splitting is simple enough with `DataFrame.str.split(' ')`, but I can't make a new column from the last entry. When I `.str.split()` the column I get a list of arrays and I don't know how to manipulate this to get a new column for m...
Do this: ``` In [43]: temp2.str[-1] Out[43]: 0 p500 1 p600 2 p700 Name: ticker ```
In Python, why doesn't an import in an exec in a function work?
12,505,047
13
2012-09-20T01:36:18Z
12,505,166
9
2012-09-20T01:54:10Z
[ "python", "function", "import", "exec" ]
I can put an import statement in a string, exec it, and it works (prints a random digit): ``` code = """ import random def f(): print random.randint(0,9) """ def f(): pass exec code f() ``` Now, if I put `exec code` and `f()` in their own function and call it, it doesn't work. ``` def test(): exec code...
What's going on here is that the module random is being imported as a local variable in test. Try this ``` def test(): exec code print globals() print locals() f() ``` will print ``` {'code': '\nimport random\ndef f():\n print random.randint(0,9)\n', '__builtins__': <module '__builtin__' (built-in...
Print not working when compiled with py2exe
12,505,383
7
2012-09-20T02:33:36Z
12,505,630
9
2012-09-20T03:16:13Z
[ "python", "printing", "py2exe" ]
this is my very simple code, printing argvs: ``` import sys argv=sys.argv for each in sys.argv: print each ``` here's the output when ran: ``` e:\python>python test1.py 1 2 3 4 5 test1.py 1 2 3 4 5 ``` I want it to be compiled, so I made one with py2exe: ``` e:\python>python setup.py py2exe ``` and my setup....
``` # ... windows = [{'script': "test1.py"}], #... ``` `windows` option is used to create GUI executables, which suppresses console output. Use `console` instead: ``` from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') setup( options = {'py2exe': {'bundle_files': 3}}, console =...
Python: Recommended way to walk complex dictionary structures imported from JSON?
12,507,206
20
2012-09-20T06:36:47Z
12,507,453
28
2012-09-20T06:58:40Z
[ "python", "json", "dictionary", "python-2.7" ]
Importing from `JSON` can get very complex and nested structures. For example: ``` {u'body': [{u'declarations': [{u'id': {u'name': u'i', u'type': u'Identifier'}, u'init': {u'type': u'Literal', u'value': 2}, u'type': u'...
If you only need to walk the dictionary, I'd suggest using a recursive `walk` function that takes a dictionary and then recursively walks through its elements. Something like this: ``` def walk(node): for key, item in node.items(): if item is a collection: walk(item) else: I...
Python: Recommended way to walk complex dictionary structures imported from JSON?
12,507,206
20
2012-09-20T06:36:47Z
12,507,546
16
2012-09-20T07:04:40Z
[ "python", "json", "dictionary", "python-2.7" ]
Importing from `JSON` can get very complex and nested structures. For example: ``` {u'body': [{u'declarations': [{u'id': {u'name': u'i', u'type': u'Identifier'}, u'init': {u'type': u'Literal', u'value': 2}, u'type': u'...
You can use recursive generator for convert your dictionary to linear lists. ``` def dict_generator(indict, pre=None): pre = pre[:] if pre else [] if isinstance(indict, dict): for key, value in indict.items(): if isinstance(value, dict): for d in dict_generator(value, [key] ...
Determine empty template variable in Django
12,507,281
5
2012-09-20T06:44:12Z
17,307,803
17
2013-06-25T21:24:37Z
[ "python", "django", "mongodb", "django-templates", "pymongo" ]
I'm not able to determine whether a variable is empty when used in the template. I've iterated through the whole collection and in each I'm looking for a variable `narrative_text`. I tested the empty variable by ``` {% ifnotequal narratives.narrative_text '' %} ``` I notice the control enters this block, but prints ...
Pipe through length and do your test against that value. ``` {% if narratives.narrative_text|length > 0 %} {{ narratives.narrative_text }} {% else %} None {% endif %} ```
Error using knnMatch with OpenCV+Python
12,508,934
6
2012-09-20T08:37:31Z
12,554,234
7
2012-09-23T16:54:29Z
[ "python", "opencv", "runtime-error" ]
I want to match two pictures using Python+OpenCV. I have used SURF to extract keypoints and descriptors from both of them. Now, I need to match these descriptors and for this reason I decided to use Flann Matcher. ``` flann_params = dict(algorithm = FLANN_INDEX_KDTREE,trees = 4) matcher = cv2.FlannBasedMatcher(fla...
I solved this problem using the correct data type with the function np.asarray() ``` raw_matches=matcher.knnMatch(np.asarray(desc1,np.float32),np.asarray(desc2,np.float32), 2) #2 ```
How can I send an xml body using requests library?
12,509,888
10
2012-09-20T09:37:56Z
12,510,559
33
2012-09-20T10:17:12Z
[ "python", "python-requests" ]
``` def request(): #encoded_xml = urllib.urlencode({'XML': read_xml()}) #encoded_xml = read_xml() headers = {'Authorization': AUTH_TOKEN,\ 'developerToken': DEVELOPER_TOKEN,\ 'clientCostumerID': CLIENT_ID} content = {'__rdxml': encoded_xml} #content = encoded_xml #c...
Just send xml bytes directly: ``` # -*- coding: utf-8 -*- import requests xml = """<?xml version='1.0' encoding='utf-8'?> <a>б</a>""" headers = {'Content-Type': 'application/xml'} # set what your server accepts print requests.post('http://httpbin.org/post', data=xml, headers=headers).text ``` ### Output ``` { "o...
In gevent, how can I dump stack traces of all running greenlets?
12,510,648
10
2012-09-20T10:22:35Z
12,553,888
12
2012-09-23T16:09:35Z
[ "python", "gevent" ]
For debugging purposes, I would like to iterate over all greenlets and obtain their trace traces -- how can I do that with gevent? Basically, I would like to do the gevent equivalent of [this](http://stackoverflow.com/questions/1032813/dump-stacktraces-of-all-active-threads).
You can use the `gc` module to iterate through all the objects on the heap and search for greenlets. Greenlets store the stack traces as an attribute `gr_frame`. ``` import gc import traceback from greenlet import greenlet for ob in gc.get_objects(): if not isinstance(ob, greenlet): continue if not ob...
How to decode an invalid json string in python
12,511,159
4
2012-09-20T10:54:13Z
12,511,364
7
2012-09-20T11:07:26Z
[ "python", "json", "python-2.7" ]
I wonder if there is a way to decode a JSON-like string. I got string: ``` '{ hotel: { id: "123", name: "hotel_name"} }' ``` It's not a valid JSON string, so I can't decode it directly with the python API. Python will only accept a stringified JSON string like: ``` '{ "hotel": { "id": "123", "name": "hotel_name"} ...
Use [demjson](http://deron.meranda.us/python/demjson/) module, which has ability to decode in non-strict mode. ``` In [1]: import demjson In [2]: demjson.decode('{ hotel: { id: "123", name: "hotel_name"} }') Out[2]: {u'hotel': {u'id': u'123', u'name': u'hotel_name'}} ```
Hooking into sqlalchemy models
12,512,662
2
2012-09-20T12:34:17Z
12,513,904
9
2012-09-20T13:39:50Z
[ "python", "orm", "sqlalchemy", "hook" ]
I'm looking to hook into the model creation cycle for sqlalchemy models. For example on create or on save (like in the Ruby ORM ActiveRecord, in fact I'm moving a model from ActiveRecord to SqlAlchemy). Events looks like what I need: <http://docs.sqlalchemy.org/en/rel_0_7/core/event.html>, but I haven't found more det...
Events are pretty simple once you get the hang of it. Here is a quick example using events ``` import uuid from sqlalchemy.event import listen from mypackage.models import Base def generate_license(mapper, connect, target): target.generate_license() class User(Base): __tablename__ = "users" id = C...
Hooking into sqlalchemy models
12,512,662
2
2012-09-20T12:34:17Z
26,611,082
8
2014-10-28T14:37:01Z
[ "python", "orm", "sqlalchemy", "hook" ]
I'm looking to hook into the model creation cycle for sqlalchemy models. For example on create or on save (like in the Ruby ORM ActiveRecord, in fact I'm moving a model from ActiveRecord to SqlAlchemy). Events looks like what I need: <http://docs.sqlalchemy.org/en/rel_0_7/core/event.html>, but I haven't found more det...
``` from sqlalchemy.event import listen_for … class User(Base): … @listen_for(User, 'before_insert') @staticmethod def generate_license(mapper, connect, self): … ``` This will return ``` NameError: name 'User' is not defined ```
reading file with missing values in python pandas
12,514,590
5
2012-09-20T14:16:45Z
12,514,711
9
2012-09-20T14:22:29Z
[ "python", "pandas" ]
I try to read .txt with missing values using pandas.read\_csv. My data is of the format: ``` 10/08/2012,12:10:10,name1,0.81,4.02,50;18.5701400N,4;07.7693770E,7.92,10.50,0.0106,4.30,0.0301 10/08/2012,12:10:11,name2,,,,,10.87,1.40,0.0099,9.70,0.0686 ``` with thousands of samples with same name of the point, gps positio...
The parameter `na_values` must be "list like" (see this [answer](http://stackoverflow.com/a/9941582/1240268)). A string is "list like" so: ``` na_values='abc' # would transform the letters 'a', 'b' and 'c' each into `nan` # is equivalent to na_values=['a','b','c']` ``` Similarly: ``` na_values='' # is equivalent to...
assertRaises fails, even the callable raises the required exception (python, unitest)
12,516,881
7
2012-09-20T16:27:34Z
12,516,955
7
2012-09-20T16:31:38Z
[ "python", "unit-testing" ]
I have the following test-code checking for an exception raising in a function. I expect the test to pass, but a failure is indicated instead. Here is the test code: ``` import unittest # define a user-defined exception class MyException(Exception): def __str__(self): return repr("ERROR: Just raised my ex...
Due to the rules of the languages, the arguments are evaluated before the code of the called function is entered (and that's generally a good thing). Therefore, `assertRaises` can't catch exceptions occuring during evaluation of arguments. The workaround (in more than one API) is that you *pass a callable* to methods l...
assertRaises fails, even the callable raises the required exception (python, unitest)
12,516,881
7
2012-09-20T16:27:34Z
12,516,956
13
2012-09-20T16:31:40Z
[ "python", "unit-testing" ]
I have the following test-code checking for an exception raising in a function. I expect the test to pass, but a failure is indicated instead. Here is the test code: ``` import unittest # define a user-defined exception class MyException(Exception): def __str__(self): return repr("ERROR: Just raised my ex...
`assertRaises` calls the function for you. By calling it yourself, the exception is raised *before* `assertRaises` can test it. Change your code to: ``` self.assertRaises(MyException, other.func) ``` and it'll work correctly. Alternatively, you can use `assertRaises` as a context manager (python 2.7 and up): ``` wi...
sqlalchemy conditional multiple filters on dynamic lazy relationship
12,517,414
5
2012-09-20T17:04:34Z
12,517,683
9
2012-09-20T17:23:44Z
[ "python", "sqlalchemy", "flask", "flask-sqlalchemy" ]
I am using sqlalchemy with the following models ``` class Page(db.Model): id= .. posts = db.relationship('Post', lazy='dynamic') class Post(db.Model): id=.. page_id=.. author= db.Column(db.String) date= db.Column(db.DateTime) ``` in the Page class I have a method to get the page's posts for a s...
`filter()` returns a new query object, but you do not store it. Replace `p` with the result each time: ``` if start_date: p = p.filter(Post.date >= start_date) if end_date: p = p.filter(Post.date <= end_date) return p ```
PyCharm autocomplete
12,517,535
9
2012-09-20T17:11:59Z
12,518,290
10
2012-09-20T18:05:04Z
[ "python", "autocomplete", "pycharm" ]
I'm completely new to Python and PyCharm and I cannot figure out why PyCharm doesn't auto-completes very simple cases such as: ``` import pickle pickle.dum[control+space or control+shift+space results nothing here] ``` I have PyCharm 2.6.2 and Python 2.7.1. What's wrong? **Add:** I'm on Mac OS 10.7.3
Can't reproduce. Make sure you have a valid Python interpreter configured for the project. Also try `File` | `Invalidate Caches`. ![pickle](http://i.stack.imgur.com/APDlD.png)
Double underscore for Python method *argument*
12,517,877
10
2012-09-20T17:38:18Z
12,517,966
11
2012-09-20T17:43:59Z
[ "python" ]
I know what double underscore means for Python class attributes/methods, but does it mean something for method argument? It looks like you cannot pass argument starting with double underscore to methods. It is confusing because you can do that for normal functions. Consider this script: ``` def egg(__a=None): re...
Name mangling applies to all identifiers with leading double underscores, [regardless of where they occur](http://docs.python.org/reference/expressions.html#atom-identifiers) (second to last sentence in that section): > This transformation is independent of the syntactical context in which the identifier is used. Thi...
Numpy Indexing: Return the rest
12,518,043
7
2012-09-20T17:48:50Z
12,518,492
7
2012-09-20T18:17:28Z
[ "python", "arrays", "numpy", "indexing", "scipy" ]
A simply example of numpy indexing: ``` In: a = numpy.arange(10) In: sel_id = numpy.arange(5) In: a[sel_id] Out: array([0,1,2,3,4]) ``` How do I return the rest of the array that are not indexed by sel\_id? What I can think of is: ``` In: numpy.array([x for x in a if x not in a[id]]) out: array([5,6,7,8,9]) ``` Is ...
For this simple 1D case, I'd actually use a boolean mask: ``` a = numpy.arange(10) include_index = numpy.arange(4) include_idx = set(include_index) #Set is more efficient, but doesn't reorder your elements if that is desireable mask = numpy.array([(i in include_idx) for i in xrange(len(a))]) ``` Now you can get your...
pip ignores dependency_links in setup.py
12,518,499
18
2012-09-20T18:17:42Z
13,587,734
32
2012-11-27T15:40:20Z
[ "python", "pip", "setuptools", "distutils", "easy-install" ]
I have dependency\_links in my setup.py: ``` ... dependency_links = ['http://github.com/robot-republic/python-s3/tarball/master.tar.gz#egg=python-s3'], ... ``` But it doesn't work. However install\_requires works fine. Maybe there are another method to set up git repo as required for setup.py?
[This answer](http://stackoverflow.com/questions/3472430/how-can-i-make-setuptools-install-a-package-thats-not-on-pypi) should help. In a nutshell, you need to specify the version (or "dev") for the `#egg=python-s3` so it looks like `#egg=python-s3-1.0.0`. Updates based on @Cerin's comment: * Pip 1.5.x has a flag to ...
scrape websites with infinite scrolling
12,519,074
19
2012-09-20T18:56:22Z
12,519,990
16
2012-09-20T19:57:52Z
[ "python", "screen-scraping", "scraper" ]
I have written many scrapers but I am not really sure how to handle infinite scrollers. These days most website etc, Facebook, Pinterest has infinite scrollers.
Most sites that have infinite scrolling do (as Lattyware notes) have a proper API as well, and you will likely be better served by using this rather than scraping. But if you must scrape... Such sites are using JavaScript to request additional content from the site when you reach the bottom of the page. All you need ...
scrape websites with infinite scrolling
12,519,074
19
2012-09-20T18:56:22Z
26,814,351
18
2014-11-08T06:07:44Z
[ "python", "screen-scraping", "scraper" ]
I have written many scrapers but I am not really sure how to handle infinite scrollers. These days most website etc, Facebook, Pinterest has infinite scrollers.
You can use selenium to scrap the infinite scrolling website like twitter or facebook. Step 1 : Install Selenium using pip ``` pip install selenium ``` Step 2 : use the code below to automate infinite scroll and extract the source code ``` from selenium import webdriver from selenium.webdriver.common.by import By f...
Python3: Invalid Syntax
12,519,554
6
2012-09-20T19:26:21Z
12,519,594
11
2012-09-20T19:28:50Z
[ "python", "python-3.x" ]
I am a beginner in Python and have been testing different kinds of sample code. When I started using Python3 instead of 2.7; I came upon a syntax error, but I don't understand how to fix that error. ``` File "app.py", line 101 except InvalidUserPass, e: ^ SyntaxError: invalid syntax ```...
Change ``` except InvalidUserPass, e: ``` to ``` except InvalidUserPass as e: ``` See [this](http://docs.python.org/tutorial/errors.html) for more info.
Recursive change-making algorithm
12,520,263
6
2012-09-20T20:17:07Z
12,520,459
12
2012-09-20T20:29:56Z
[ "python", "algorithm", "recursion", "dynamic-programming", "coin-change" ]
Given a target amount and a list of coin denominations, my code is supposed to find the fewest coins needed to reach the target amount. Examples: * `C(48, [1, 5, 10, 25, 50]) = 6` + we can make 48 from 3x`25` + 3x`1`, so 6 coins are required * `C(48, [1, 7, 24, 42]) = 2` + 48 = 2x`24`, so 2 coins are sufficient...
It's the [change-making](https://en.wikipedia.org/wiki/Change-making_problem) problem. Here's the standard recursive solution, `V` is the list of coins and `C` the target amount of money: ``` def min_change(V, C): def min_coins(i, aC): if aC == 0: return 0 elif i == -1 or aC < 0: ...
Installing PIP packages to a Virtualenv using a download cache
12,521,552
9
2012-09-20T22:00:55Z
12,525,243
18
2012-09-21T06:21:09Z
[ "python", "django", "pip", "pypi" ]
What's the proper way to install pip packages to a virtualenv using cached packages? I've tried setting `--timeout=360` and `--use-mirrors`, but pypi performance is so flakey, it routinely hangs or disconnects, making deployments a crapshoot. So, my plan was to use the --download-cache option to pre-download all packa...
The problem seems to be that `--download-cache` can only be used to specify the cache for downloading, not for installing. Therefore `pip` is still looking at `/usr/local/myapp/.env/build/Django` instead of `/usr/local/pip/cache`. Have you tried moving ``` pip install --upgrade --timeout=120 --use-mirrors --no-install...
usage of __init__.py
12,521,839
5
2012-09-20T22:29:45Z
12,521,941
11
2012-09-20T22:39:12Z
[ "python" ]
I use `__init__.py` to run checks when I do `from myprojects.something import blabla`. Today I started using `pyzmq` and I wanted to see what's going on behind the scenes. So I browsed the code in github and I find (for me) some strange usage of `__init__.py` there that I cannot explain myself. For example [`zmq/core...
The `__all__` is for when someone does `from module import *` as documented [here](http://docs.python.org/tutorial/modules.html?highlight=__all__#importing-from-a-package). > The only solution is for the package author to provide an explicit > index of the package. The import statement uses the following > convention:...
How can I tail a log file in Python?
12,523,044
36
2012-09-21T01:13:58Z
12,523,119
21
2012-09-21T01:25:39Z
[ "python", "tail" ]
I'd like to make the output of tail -F or something similar available to me in Python without blocking or locking. I've found some really old code to do that [here](http://code.activestate.com/recipes/436477-filetailpy/), but I'm thinking there must be a better way or a library to do the same thing by now. Anyone know ...
Using the [sh module](http://amoffat.github.io/sh/) (pip install sh): ``` from sh import tail # runs forever for line in tail("-f", "/var/log/some_log_file.log", _iter=True): print(line) ``` [update] Since sh.tail with `_iter`=True is a generator, you can: ``` import sh tail = sh.tail("-f", "/var/log/some_log_f...
How can I tail a log file in Python?
12,523,044
36
2012-09-21T01:13:58Z
12,523,302
20
2012-09-21T01:59:54Z
[ "python", "tail" ]
I'd like to make the output of tail -F or something similar available to me in Python without blocking or locking. I've found some really old code to do that [here](http://code.activestate.com/recipes/436477-filetailpy/), but I'm thinking there must be a better way or a library to do the same thing by now. Anyone know ...
The only *portable* way to `tail -f` a file appears to be, in fact, to read from it and retry (after a `sleep`) if the `read` returns 0. The `tail` utilities on various platforms use platform-specific tricks (e.g. `kqueue` on BSD) to efficiently tail a file forever without needing `sleep`. Therefore, implementing a go...
How can I tail a log file in Python?
12,523,044
36
2012-09-21T01:13:58Z
12,523,371
32
2012-09-21T02:09:27Z
[ "python", "tail" ]
I'd like to make the output of tail -F or something similar available to me in Python without blocking or locking. I've found some really old code to do that [here](http://code.activestate.com/recipes/436477-filetailpy/), but I'm thinking there must be a better way or a library to do the same thing by now. Anyone know ...
## Non Blocking If you are on linux (as windows does not support calling select on files) you can use the subprocess module along with the select module. ``` import time import subprocess import select f = subprocess.Popen(['tail','-F',filename],\ stdout=subprocess.PIPE,stderr=subprocess.PIPE) p = select.pol...
f2py: Specifying real precision in fortran when interfacing with python?
12,523,524
5
2012-09-21T02:35:54Z
12,524,403
10
2012-09-21T04:46:45Z
[ "python", "fortran90", "f2py" ]
I am playing around with f2py. I'm a bit confused about numpy intrinsic types vs. fortran 90 types. It seems like I can only use single precision reals in fortran 90, when interacting with python. Let me illustrate with an example: Say I have this fortran 90 module, test.f90, to be compiled with f2py and imported in p...
In your first example, I don't know why you say it seems like f2py doesn't accept double precision, when `test.test.r_dp` *is* double precision. A numpy array that shows a value with a decimal point and no explicit dtype is a double precision array. The second example shows a limitation in F2PY's handling of type defi...
getting value of the maximum key in dictionary (python)
12,523,876
2
2012-09-21T03:34:22Z
12,523,886
10
2012-09-21T03:35:45Z
[ "python", "dictionary" ]
I only found here how can I get the key of the maximum value: ``` max(d, key=d.get()) ``` but I need to search the maximum key and return the value of this key. thanks,
To get the maximum key ``` max(d) ``` And for the value, just look it up in the dictionary ``` d[max(d)] ``` Note: You can also use `max(d.keys())`, but it a bit slower because it needs to build a temporary list ``` $ python -m timeit -s 'd={x:str(x) for x in range(10000)}' 'max(d)' 1000 loops, best of 3: 377 usec...
How do you implement "#ifdef" in python?
12,524,570
15
2012-09-21T05:08:08Z
12,524,872
16
2012-09-21T05:42:53Z
[ "python", "preprocessor" ]
Programming in `C` I used to have code sections only used for debugging purposes (logging commands and the like). Those statements could be completely disabled for production by using `#ifdef` pre-processor directives, like this: ``` #ifdef MACRO controlled text #endif /* MACRO */ ``` What is the best way to do ...
If you just want to disable logging methods, use the `logging` module. If the log level is set to exclude, say, debug statements, then `logging.debug` will be very close to a no-op (it just checks the log level and returns without interpolating the log string). If you want to actually remove chunks of code at bytecode...
Encrypt & Decrypt using PyCrypto AES 256
12,524,994
73
2012-09-21T05:54:41Z
12,525,124
8
2012-09-21T06:08:30Z
[ "python", "encryption", "padding", "pycrypto", "initialization-vector" ]
I'm trying to build two functions using PyCrypto that accept two parameters: the message and the key, and then encrypt/decrypt the message. I found several links on the web to help me out, but each one of them has flaws: [This one at codekoala](http://www.codekoala.com/blog/2009/aes-encryption-python-using-pycrypto/)...
You can get a passphrase out of an arbitrary password by using a cryptographic hash function (*NOT* Python's builtin `hash`) like SHA-1 or SHA-256. Python includes support for both in its standard library: ``` import hashlib hashlib.sha1("this is my awesome password").digest() # => a 20 byte string hashlib.sha256("an...
Encrypt & Decrypt using PyCrypto AES 256
12,524,994
73
2012-09-21T05:54:41Z
12,525,165
105
2012-09-21T06:12:54Z
[ "python", "encryption", "padding", "pycrypto", "initialization-vector" ]
I'm trying to build two functions using PyCrypto that accept two parameters: the message and the key, and then encrypt/decrypt the message. I found several links on the web to help me out, but each one of them has flaws: [This one at codekoala](http://www.codekoala.com/blog/2009/aes-encryption-python-using-pycrypto/)...
You may need the following two functions to pad(when do encryption) and unpad(when do decryption) when the length of input is not a multiple of BLOCK\_SIZE. ``` BS = 16 pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) unpad = lambda s : s[:-ord(s[len(s)-1:])] ``` So you're asking the length of key? You...
Encrypt & Decrypt using PyCrypto AES 256
12,524,994
73
2012-09-21T05:54:41Z
21,928,790
42
2014-02-21T08:10:37Z
[ "python", "encryption", "padding", "pycrypto", "initialization-vector" ]
I'm trying to build two functions using PyCrypto that accept two parameters: the message and the key, and then encrypt/decrypt the message. I found several links on the web to help me out, but each one of them has flaws: [This one at codekoala](http://www.codekoala.com/blog/2009/aes-encryption-python-using-pycrypto/)...
Here is my implementation and works for me with some fixes and enhances the alignment of the key and secret phrase with 32 bytes and iv to 16 bytes: ``` import base64 import hashlib from Crypto import Random from Crypto.Cipher import AES class AESCipher(object): def __init__(self, key): self.bs = 32 ...
Normalize data in pandas
12,525,722
29
2012-09-21T07:04:23Z
12,525,836
69
2012-09-21T07:14:15Z
[ "python", "pandas", "numpy" ]
Suppose I have a pandas data frame df: I want to calculate the column wise mean of a data frame, This is easy: ``` df.apply(average) ``` then the column wise range max(col) - min (col). this is easy again: ``` df.apply(max) - df.apply(min) ``` Now for each element I want to subtract its columns mean and divide by...
``` In [92]: df Out[92]: a b c d A -0.488816 0.863769 4.325608 -4.721202 B -11.937097 2.993993 -12.916784 -1.086236 C -5.569493 4.672679 -2.168464 -9.315900 D 8.892368 0.932785 4.535396 0.598124 In [93]: df_norm = (df - df.mean()) / (df.max() - df.min()) In [94]: df_n...
Normalize data in pandas
12,525,722
29
2012-09-21T07:04:23Z
33,250,288
11
2015-10-21T03:10:46Z
[ "python", "pandas", "numpy" ]
Suppose I have a pandas data frame df: I want to calculate the column wise mean of a data frame, This is easy: ``` df.apply(average) ``` then the column wise range max(col) - min (col). this is easy again: ``` df.apply(max) - df.apply(min) ``` Now for each element I want to subtract its columns mean and divide by...
You can use `apply` for this, and it's a bit neater: ``` import numpy as np import pandas as pd np.random.seed(1) df = pd.DataFrame(np.random.randn(4,4)* 4 + 3) 0 1 2 3 0 9.497381 0.552974 0.887313 -1.291874 1 6.461631 -6.206155 9.979247 -0.044828 2 4.276156 2.002518 8.8484...
Callback for celery apply_async
12,526,606
6
2012-09-21T08:09:48Z
13,494,345
21
2012-11-21T13:27:27Z
[ "python", "celery" ]
I use `celery` in my application to run periodic tasks. Let's see simple example below ``` from myqueue import Queue @perodic_task(run_every=timedelta(minutes=1)) def process_queue(): queue = Queue() uid, questions = queue.pop() if uid is None: return job = group(do_stuff(q) for q in questions...
Subclass the Task class and overload the on\_success and on\_failure functions: ``` class CallbackTask(Task): def on_success(self, retval, task_id, args, kwargs): pass def on_failure(self, exc, task_id, args, kwargs, einfo): pass @celery.task(base=CallbackTask) # this does the trick def add...
Custom directives in Sphinx
12,527,783
12
2012-09-21T09:26:47Z
12,836,645
9
2012-10-11T09:41:55Z
[ "python", "documentation", "python-sphinx", "restructuredtext" ]
I'm currently documenting a rest API written in Python. All the project's documentation is created using Sphinx, for the REST API I would like to create some special directvies. For instance, let's say I have this resource defined: ``` @resource("/user/<email>", method="GET") def user_details (email): """ Returns ...
Sphinx can be extended with custom directives via "[Sphinx Extensions](http://sphinx.pocoo.org/extensions.html)". That is, you will need to implement a Sphinx extension providing the `query_param` custom directive, and add this extension to your Sphinx project. Sphinx documentation provides [a tutorial](http://sphinx-...
Passing the '+' character in a POST request in Python
12,527,959
5
2012-09-21T09:37:36Z
12,528,097
7
2012-09-21T09:45:15Z
[ "python", "python-requests" ]
I am trying to do some automation in a Python script and I have run into a problem. I am trying to do a POST to a server. ``` url = 'http://www.example.com' params = {'arg0': 'value', 'arg1': '+value'} f = urllib.urlopen(url, urllib.urlencode(params)) print f.read() ``` I have done a wireshark capture of the equival...
The `+` character is the proper encoding for a space when quoting GET or POST data. Thus, a literal `+` character needs to be escaped as well, lest it be decoded to a space on the other end. See RFC 2396, [section 2.2](https://tools.ietf.org/html/rfc2396#section-2.2), [section 3.4](https://tools.ietf.org/html/rfc2396#s...
how to "add" things together python
12,530,686
2
2012-09-21T12:31:01Z
12,530,741
10
2012-09-21T12:35:33Z
[ "python" ]
I wrote a function like this, the `op` gives a operation sign which like `'+','-','*','/'` or more, the code "adds" everything use the given operator, **Here is the code:** ``` def arithmetic(op,*args): result = args[0] for x in args[1:]: if op =='+': result += x elif op == '-': ...
You can use the corresponding [operators](http://docs.python.org/library/operator.html): ``` import operator def arithmetic(opname, *args): op = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.div}[opname] result = args[0] for x in args[1:]: resu...
How to make this python script fast? (benchmarking related to branch prediction from a post from here)
12,530,812
4
2012-09-21T12:41:21Z
24,399,639
7
2014-06-25T03:20:22Z
[ "python", "optimization", "branch-prediction" ]
From [here - a branching prediction problem](http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array), I started to write the Python version of the program to check the runtime of the sorted/unsorted versions in Python. I tried sorted first. Here's the code: ``` impo...
I started with the answer by @mgilson and reworked it a bit. I wanted to test the "decision bit" and lookup table techniques as discussed in my answer to the original question: <http://stackoverflow.com/a/17782979/166949> I made a few changes to the original. Some were just style things that reflect my personal prefer...
String split on new line, tab and some number of spaces
12,533,955
20
2012-09-21T15:54:34Z
12,533,983
44
2012-09-21T15:56:07Z
[ "python", "regex", "split" ]
I'm trying to perform a string split on a set of somewhat irregular data that looks something like: ``` \n\tName: John Smith \n\t Home: Anytown USA \n\t Phone: 555-555-555 \n\t Other Home: Somewhere Else \n\t Notes: Other data \n\tName: Jane Smith \n\t Misc: Data with spaces ``` I'd like to convert this into a ...
Just use [.strip()](http://docs.python.org/library/stdtypes.html#str.strip), it removes all whitespace for you, including tabs and newlines, while splitting. The splitting itself can then be done with [`data_string.splitlines()`](http://docs.python.org/library/stdtypes.html#str.splitlines): ``` [s.strip() for s in dat...
Memory Usage in Python: What's the difference between memory_profiler and guppy?
12,534,794
4
2012-09-21T16:53:46Z
12,535,427
7
2012-09-21T17:36:44Z
[ "python", "memory-profiling" ]
I'm thoroughly confused about the memory usage of a specific python script. I guess I don't really know how to profile the usage despite [advice](http://stackoverflow.com/questions/110259/python-memory-profiler) from several SO Questions/[Answers](http://stackoverflow.com/a/552810/717357). My questions are: **What's t...
> What's the difference between memory\_profiler and guppy.hpy? Do you understand the difference between your internal view of the heap and the OS's external view of your program? (For example, when the Python interpreter calls `free` on 1MB, that doesn't immediately—or maybe even ever—return 1MB worth of pages to...
Why is slice assignment faster than `list.insert`?
12,537,716
18
2012-09-21T20:26:10Z
12,537,894
12
2012-09-21T20:42:05Z
[ "python", "performance", "optimization", "python-internals" ]
Inspired by [this nice answer](http://stackoverflow.com/a/12537489/748858), Here's a benchmark: ``` import timeit def test1(): a = [1,2,3] a.insert(0,1) def test2(): a = [1,2,3] a[0:0]=[1] print (timeit.timeit('test1()','from __main__ import test1')) print (timeit.timeit('test2()','from __main__ im...
Your first test case has to call the method `insert` on the list `a`, whereas all the operations in `test2` are handled directly in byte code. Note the `CALL_FUNCTION` in the disassembly of `test1` below. Calling functions is moderately expensive in Python: certainly expensive enough to account for a few percent differ...
Python "private" name mangling and instance vs class attributes
12,537,904
6
2012-09-21T20:42:43Z
12,537,917
9
2012-09-21T20:44:12Z
[ "python", "attributes", "private-members", "name-mangling", "underscores" ]
I was writing a decorator that needs to access private variables and found this discrepancy. Can anyone explain this? (Python 2.5) Naming mangling works as expected for attributes defined in the class: ``` >>> class Tester(object): ... __foo = "hi" >>> t = Tester() >>> t._Tester__foo 'hi' ``` Instance attribute...
That is actually *not* correct. Name mangling takes place at class creation time; any functions that refer to mangled names are adjusted as well. I cannot reproduce your example, at least not in Python versions 2.4, 2.5, 2.6, 3.1 and 3.2 on the Mac: ``` >>> class Tester(object): ... def __init__(self): ... ...
Python module "cx_Oracle" module could not be found
12,538,238
8
2012-09-21T21:13:35Z
19,552,263
8
2013-10-23T21:05:21Z
[ "python", "oracle", "module", "cx-oracle" ]
I recently installed cx\_Oracle module on my machine, in order to connect to a remote Oracle database server. (I have no Oracle client at my side). * Python: Version 2.7 x86 * Oracle: Verision 11.1.X x64 * Cx\_Oracle:Verion-5.1.2-11g.win32-py2.7 Then everytime I run my script, it fails and print the following message...
``` # - This import requires appropriate oraocciXX.dll to be available in PATH (on windows) # (Probably LD_LIBRARY_PATH or LD_LIBRARY_PATH64 on POSIX) # where XX is the oracle DB version, e.g. oraocci11.dll for Oracle 11g. # - This dll is part of the Oracle Instant client pkg available here: # http://www.orac...
How do I find the longest string in Python?
12,538,586
8
2012-09-21T21:45:21Z
12,538,604
33
2012-09-21T21:47:16Z
[ "python", "string", "string-length" ]
Something like `max(len(s1), len(s2))` will only return the maximum length. But if I actually want to find out which string is longer, and perhaps save it to another string, how is that done? `max(s1,s2)` seems to return the string with the larger value, but not necessarily the longest. Note: this has to be done witho...
`max` takes a `key` function which causes `max` to take the max `key(val)` for each `val`, yet still return the `val`, to wit: ``` >>> max("foobar", "angstalot") 'foobar' >>> max("foobar", "angstalot", key=len) 'angstalot' ```
What does the underscore represent in Python?
12,539,245
5
2012-09-21T23:09:06Z
12,539,279
10
2012-09-21T23:13:45Z
[ "python" ]
I am kind of new to Python, so I am trying to read over existing code. I am a little confused on the syntax of this though. For example: ``` rlist, _, _ = select.select(sockets, [], []) ``` I understand that `select.select()` takes 3 lists (and I assume `[]` just means empty list), but is the `_` used to denote a pl...
It's just the name of a variable! Usually people use `_` for variables that are temporary or insignificant. As other people have stated, `_` is a common alias for gettext, a translation library. You can identify when it's being used as gettext if you see it called as a function, eg. `_('Hello, world!')`. **Protip:** ...
How to organize multiple python files into a single module without it behaving like a package?
12,540,290
16
2012-09-22T02:51:12Z
12,540,337
10
2012-09-22T03:02:00Z
[ "python", "module", "package" ]
Is there a way to use `__init__.py` to organize multiple files into a **module**? Reason: Modules are easier to use than packages, because they don't have as many layers of namespace. Normally it makes a package, this I get. Problem is with a package, 'import thepackage' gives me an empty namespace. Users must then e...
You can sort of do it, but it's not really a good idea and you're fighting against the way Python modules/packages are supposed to work. By importing appropriate names in `__init__.py` you can make them accessible in the package namespace. By deleting module names you can make them inaccessible. (For why you need to de...
Test if an index of a list exists
12,540,600
4
2012-09-22T04:07:21Z
12,540,662
7
2012-09-22T04:18:44Z
[ "python" ]
Okay, so this is actually two questions. First, I want to know if there is a way to test if an index of a list exists. For example, I want to increment list[i] each time a given condition is true using code like `list[i] += 1`, but if the index doesn't exists, I'm given an error. So I want to set up a test that, in the...
Test if an index exists: ``` if 0 <= i < len(list): ... do something with list[i] ... else: ... i is out of bounds, do something else ... ``` In this situation, you're probably better off using a [`dict`](http://docs.python.org/library/stdtypes.html#dict) instead of an array, and possibly a [`defaultdict`](http://doc...
Test if an index of a list exists
12,540,600
4
2012-09-22T04:07:21Z
12,540,663
8
2012-09-22T04:18:59Z
[ "python" ]
Okay, so this is actually two questions. First, I want to know if there is a way to test if an index of a list exists. For example, I want to increment list[i] each time a given condition is true using code like `list[i] += 1`, but if the index doesn't exists, I'm given an error. So I want to set up a test that, in the...
It sounds like what you really want is a `defaultdict` -- not a list so much as a mapping of integers to some sort of count of the number of times you've seen them. (this is really close to the concept of autovivificaiton in perl, if you've used that before) This code would work: ``` from collections import defaultd...
How to get Excel cell properties in Python
12,540,856
4
2012-09-22T05:01:31Z
12,541,180
9
2012-09-22T06:03:18Z
[ "python", "xlrd" ]
Actually I am using xlrd module 0.8 version, but I don't know how to read cell properties like background color, font, and whether cell is locked. I tried to use ``` import xlrd wb = xlrd.open_workbook(...) sh = wb.sheet_by_index(...) sh.sh._cell_xf_indexes(2, 2) ``` It raises an error saying formatting information ...
The following works for me, using xlrd version 0.7.6: ``` from xlrd import open_workbook wb = open_workbook('tmp.xls', formatting_info=True) sheet = wb.sheet_by_name("1") cell = sheet.cell(6, 0) print "cell.xf_index is", cell.xf_index fmt = wb.xf_list[cell.xf_index] print "type(fmt) is", type(fmt) print print "fmt.du...
what is the most efficient way to turn a list in python
12,541,074
3
2012-09-22T05:42:42Z
12,541,099
10
2012-09-22T05:46:38Z
[ "python" ]
so I have this list in python, ``` a= [[1,2,3,4], [2,4,5,1], [3,4,6,2], [2,3,4,5]] ``` and want to turn the list reading horizontally to vertically. ``` b= [[1,2,3,2], [2,4,4,3], [3,5,6,4], [4,1,2,5]] ``` what is the best way to do it, and most efficient way to do it? i'm pre...
You can do it like that: ``` zip(*your_list) ``` Proof: ``` >>> a = [[1, 2, 3, 4], [2, 4, 5, 1], [3, 4, 6, 2], [2, 3, 4, 5]] >>> zip(*a) [(1, 2, 3, 2), (2, 4, 4, 3), (3, 5, 6, 4), (4, 1, 2, 5)] ```
what is the most efficient way to turn a list in python
12,541,074
3
2012-09-22T05:42:42Z
12,541,101
8
2012-09-22T05:47:44Z
[ "python" ]
so I have this list in python, ``` a= [[1,2,3,4], [2,4,5,1], [3,4,6,2], [2,3,4,5]] ``` and want to turn the list reading horizontally to vertically. ``` b= [[1,2,3,2], [2,4,4,3], [3,5,6,4], [4,1,2,5]] ``` what is the best way to do it, and most efficient way to do it? i'm pre...
Check out [numpy](http://numpy.scipy.org/) library. You can put your list into an array and transpose it like this: ``` a = array ([[1,2,3,4], [2,4,5,1], [3,4,6,2], [2,3,4,5]]) a.transpose() ``` P.S.: Explanation of [Tadeck](http://stackoverflow.com/users/548696/tadeck)'s solution is very easy. `...
Flask - nested rest api - use something other than methodview or have I made a bad design?
12,541,129
5
2012-09-22T05:53:15Z
12,541,130
7
2012-09-22T05:53:15Z
[ "python", "api", "rest", "flask" ]
Just starting off with Flask, following along at <http://flask.pocoo.org/docs/views/> Say I have a basic REST api, in this case for symptoms: ``` / GET - list POST - create /<symptomid> GET - detail PUT - replace PATCH - patch DELETE - delete ``` I can implement this pretty cleanly with Flas...
I think the design is ok. `MethodView` should be pretty awesome for it. You can put the routes together like so: ``` class SymptomDiagnosisAPI(MethodView): """ /<symptom_id>/diagnoses/ GET - list diags for symptoms POST - {id: diagid} - create relation with diagnosis /<symptom_id>/diagnose...
Python 3: Asterisk in print function
12,542,544
13
2012-09-22T09:24:17Z
12,542,649
13
2012-09-22T09:39:23Z
[ "python", "python-3.x" ]
Let's have a look: ``` print([object, ...], *, sep=' ', end='\n', file=sys.stdout) ``` <http://docs.python.org/py3k/library/functions.html?highlight=print#print> How can we interpret that `'*'`? Usually an asterisk ('\*') means numerous objects. But herein it is a mystery to me. Between two commas... I'm even afraid...
It means that the following arguments are keyword-only i.e., you can't supply them as positional arguments, you must use their names e.g.: ``` >>> def f(*, a): pass ... >>> f(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: f() takes exactly 0 positional arguments (1 given) >>> f...
Python 3: Asterisk in print function
12,542,544
13
2012-09-22T09:24:17Z
12,542,650
15
2012-09-22T09:39:25Z
[ "python", "python-3.x" ]
Let's have a look: ``` print([object, ...], *, sep=' ', end='\n', file=sys.stdout) ``` <http://docs.python.org/py3k/library/functions.html?highlight=print#print> How can we interpret that `'*'`? Usually an asterisk ('\*') means numerous objects. But herein it is a mystery to me. Between two commas... I'm even afraid...
That's an error in the documentation, inserted by someone applying a new Python 3 feature to places where it shouldn't be used. It has since been fixed (see [issue 15831](http://bugs.python.org/issue15831)). The function signatures in the document used is given in a psuedo-formal-grammar form, but adding in the `*` ma...
xvfb failed to start in ubuntu
12,542,675
3
2012-09-22T09:42:29Z
12,793,696
8
2012-10-09T06:02:37Z
[ "python", "qt", "ubuntu", "webkit", "xvfb" ]
I trying to get a screen shot by using the following two tools (something relative to qt, webkit and etc. maybe) * <https://github.com/adamn/python-webkit2png> * <http://cutycapt.sourceforge.net/> when run it on server using xvfb-run following the guide of them, I got the error: Xvfb failed to start then I searched ...
It works when I remove "-server-args". Try doing that. ``` xvfb-run --auto-servernum --server-num=1 python webkit2png.py --url=http://google.com --out=test.png ``` This is the command you're looking for.
Python: iterating over list vs over dict items efficiency
12,543,837
5
2012-09-22T12:38:16Z
12,543,887
15
2012-09-22T12:44:32Z
[ "python", "performance", "list", "dictionary" ]
Is iterating over `some_dict.items()` as efficient as iterating over a list of the same items in CPython?
It depends on which version of Python you're using. In Python 2, `some_dict.items()` creates a new list, which takes up some additional time and uses up additional memory. On the other hand, once the list is created, it's a list, and so should have identical performance characteristics after the overhead of list creati...
How to I get the current IPython Notebook name
12,544,056
23
2012-09-22T13:09:59Z
13,055,551
12
2012-10-24T18:35:29Z
[ "python", "ipython" ]
I am trying to obtain the current NoteBook name when running the ipython notebook. I know I can see it at the top of the notebook. What I am after something like ``` currentNotebook = IPython.foo.bar.notebookname() ``` I need to get the name in a variable.
As already mentioned you probably aren't really supposed to be able to do this, but I did find a way. It's a flaming hack though so don't rely on this at all: ``` import json import os import urllib2 import IPython from IPython.lib import kernel connection_file_path = kernel.get_connection_file() connection_file = os....
How to I get the current IPython Notebook name
12,544,056
23
2012-09-22T13:09:59Z
23,619,544
11
2014-05-12T21:54:21Z
[ "python", "ipython" ]
I am trying to obtain the current NoteBook name when running the ipython notebook. I know I can see it at the top of the notebook. What I am after something like ``` currentNotebook = IPython.foo.bar.notebookname() ``` I need to get the name in a variable.
I have the following which works with IPython 2.0. I observed that the name of the notebook is stored as the value of the attribute `'data-notebook-name'` in the `<body>` tag of the page. Thus the idea is first to ask Javascript to retrieve the attribute --javascripts can be invoked from a codecell thanks to the `%%jav...
How to I get the current IPython Notebook name
12,544,056
23
2012-09-22T13:09:59Z
30,942,416
11
2015-06-19T15:55:59Z
[ "python", "ipython" ]
I am trying to obtain the current NoteBook name when running the ipython notebook. I know I can see it at the top of the notebook. What I am after something like ``` currentNotebook = IPython.foo.bar.notebookname() ``` I need to get the name in a variable.
On Jupyter 3.0 the following works. Here I'm showing the entire path on the Jupyter server, not just the notebook name: To store the `NOTEBOOK_FULL_PATH` on the current notebook front end: ``` %%javascript var nb = IPython.notebook; var kernel = IPython.notebook.kernel; var command = "NOTEBOOK_FULL_PATH = '" + nb.bas...
Parsing apache log files
12,544,510
19
2012-09-22T14:15:29Z
12,544,587
30
2012-09-22T14:25:18Z
[ "python", "file-io" ]
I just started learning Python and would like to read an Apache log file and put parts of each line into different lists. line from the file > 172.16.0.3 - - [25/Sep/2002:14:04:19 +0200] "GET / HTTP/1.1" 401 - "" "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827" according to [Apache website](http://ht...
This is a job for [regular expressions](http://docs.python.org/howto/regex.html). For example: ``` line = '172.16.0.3 - - [25/Sep/2002:14:04:19 +0200] "GET / HTTP/1.1" 401 - "" "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827"' regex = '([(\d\.)]+) - - \[(.*?)\] "(.*?)" (\d+) - "(.*?)" "(.*?)"' import...
Parsing apache log files
12,544,510
19
2012-09-22T14:15:29Z
12,544,831
11
2012-09-22T14:54:36Z
[ "python", "file-io" ]
I just started learning Python and would like to read an Apache log file and put parts of each line into different lists. line from the file > 172.16.0.3 - - [25/Sep/2002:14:04:19 +0200] "GET / HTTP/1.1" 401 - "" "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827" according to [Apache website](http://ht...
Use a regular expression to split a row into separate "tokens": ``` >>> row = """172.16.0.3 - - [25/Sep/2002:14:04:19 +0200] "GET / HTTP/1.1" 401 - "" "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827" """ >>> import re >>> map(''.join, re.findall(r'\"(.*?)\"|\[(.*?)\]|(\S+)', row)) ['172.16.0.3', '-', '...