title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
How to print a list more nicely? | 1,524,126 | <p>This is similar to <a href="http://stackoverflow.com/questions/1523660/how-to-print-a-list-in-python-nicely">How to print a list in Python ânicelyâ</a>, but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even better in columns.</p>
<pre><code>foolist = ['... | 6 | 2009-10-06T07:43:58Z | 1,525,926 | <pre><code>from itertools import izip_longest, islice
L = ['exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf',
'pdcurses-devel', 'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel',
'qgis1.1', 'php_mapscript']
def columnize(sequence, columns=2):
size, remainder = divmod(len(sequence), columns)
... | -1 | 2009-10-06T14:26:39Z | [
"python",
"printing"
] |
How to print a list more nicely? | 1,524,126 | <p>This is similar to <a href="http://stackoverflow.com/questions/1523660/how-to-print-a-list-in-python-nicely">How to print a list in Python ânicelyâ</a>, but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even better in columns.</p>
<pre><code>foolist = ['... | 6 | 2009-10-06T07:43:58Z | 25,048,690 | <p>This answer uses the same method in the answer by @Aaron Digulla, with slightly more pythonic syntax. It might make some of the above answers easier to understand.</p>
<pre><code>>>> for a,b,c in zip(foolist[::3],foolist[1::3],foolist[2::3]):
>>> print '{:<30}{:<30}{:<}'.format(a,b,c)... | 7 | 2014-07-30T23:35:50Z | [
"python",
"printing"
] |
How to print a list more nicely? | 1,524,126 | <p>This is similar to <a href="http://stackoverflow.com/questions/1523660/how-to-print-a-list-in-python-nicely">How to print a list in Python ânicelyâ</a>, but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even better in columns.</p>
<pre><code>foolist = ['... | 6 | 2009-10-06T07:43:58Z | 27,299,462 | <p>Found this question as a met almost the same task. And I've created function to print list in multi columns with the number of columns as parameter. Maybe not so elegant as one-liner solutions, but it could be useful for someone.</p>
<p>However, it handles incomplete lists, ex.: it can print list of 11 in 3 rows.</... | 0 | 2014-12-04T16:49:18Z | [
"python",
"printing"
] |
How to print a list more nicely? | 1,524,126 | <p>This is similar to <a href="http://stackoverflow.com/questions/1523660/how-to-print-a-list-in-python-nicely">How to print a list in Python ânicelyâ</a>, but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even better in columns.</p>
<pre><code>foolist = ['... | 6 | 2009-10-06T07:43:58Z | 30,861,871 | <p>Here's my solution. (<a href="https://gist.github.com/critiqjo/2ca84db26daaeb1715e1" rel="nofollow">Copy in GitHub gist</a>)</p>
<p>It takes terminal width as input and displays only as many columns that can be fit in it.</p>
<pre><code>def col_print(lines, term_width=80, indent=0, pad=2):
n_lines = len(lines)
... | 1 | 2015-06-16T07:57:54Z | [
"python",
"printing"
] |
How to print a list more nicely? | 1,524,126 | <p>This is similar to <a href="http://stackoverflow.com/questions/1523660/how-to-print-a-list-in-python-nicely">How to print a list in Python ânicelyâ</a>, but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even better in columns.</p>
<pre><code>foolist = ['... | 6 | 2009-10-06T07:43:58Z | 34,551,419 | <p>Here's a solution in python 3.4 that automatically detects terminal width and takes it into account. Tested on Linux and Mac.</p>
<pre><code>def column_print(list_to_print, column_width=40):
import os
term_height, term_width = os.popen('stty size', 'r').read().split()
total_columns = int(term_width) // ... | 0 | 2015-12-31T20:37:17Z | [
"python",
"printing"
] |
How to print a list more nicely? | 1,524,126 | <p>This is similar to <a href="http://stackoverflow.com/questions/1523660/how-to-print-a-list-in-python-nicely">How to print a list in Python ânicelyâ</a>, but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even better in columns.</p>
<pre><code>foolist = ['... | 6 | 2009-10-06T07:43:58Z | 36,085,705 | <p>Inspired by gimel's answer, <a href="http://stackoverflow.com/a/1524333/2352216">above</a>.</p>
<pre><code>import math
def list_columns(obj, cols=4, columnwise=True, gap=4):
"""
Print the given list in evenly-spaced columns.
Parameters
----------
obj : list
The list to be printed.
... | 3 | 2016-03-18T13:29:42Z | [
"python",
"printing"
] |
Does anyone know a way to scramble the elements in a list? | 1,524,160 | <pre><code>thelist = ['a','b','c','d']
</code></pre>
<p>How I can to scramble them in Python?</p>
| 5 | 2009-10-06T07:55:21Z | 1,524,176 | <p>Use the <a href="http://docs.python.org/library/random.html#random.shuffle"><code>random.shuffle()</code></a> function:</p>
<pre><code>random.shuffle(thelist)
</code></pre>
| 6 | 2009-10-06T07:59:16Z | [
"python",
"random"
] |
Does anyone know a way to scramble the elements in a list? | 1,524,160 | <pre><code>thelist = ['a','b','c','d']
</code></pre>
<p>How I can to scramble them in Python?</p>
| 5 | 2009-10-06T07:55:21Z | 1,524,180 | <p>Use the <code>shuffle</code> function from the <code>random</code> module:</p>
<pre><code>>>> from random import shuffle
>>> thelist = ['a','b','c','d']
>>> shuffle(thelist)
>>> thelist
['c', 'a', 'b', 'd']
</code></pre>
| 5 | 2009-10-06T07:59:44Z | [
"python",
"random"
] |
Does anyone know a way to scramble the elements in a list? | 1,524,160 | <pre><code>thelist = ['a','b','c','d']
</code></pre>
<p>How I can to scramble them in Python?</p>
| 5 | 2009-10-06T07:55:21Z | 1,524,181 | <pre><code>import random
random.shuffle(thelist)
</code></pre>
<p>Note, this shuffles the list in-place.</p>
| 9 | 2009-10-06T08:00:04Z | [
"python",
"random"
] |
Does anyone know a way to scramble the elements in a list? | 1,524,160 | <pre><code>thelist = ['a','b','c','d']
</code></pre>
<p>How I can to scramble them in Python?</p>
| 5 | 2009-10-06T07:55:21Z | 1,524,182 | <pre><code>>>> import random
>>> thelist = ['a', 'b', 'c', 'd']
>>> random.shuffle(thelist)
>>> thelist
['d', 'a', 'c', 'b']
</code></pre>
<p>Your result will (hopefully!) vary.</p>
| 12 | 2009-10-06T08:00:06Z | [
"python",
"random"
] |
How to have an error but continue the script in python? | 1,524,216 | <p>Suppose I have this code in Python:</p>
<pre><code>l = dict['link']
t = dict['title'] <<<<<<<<error here, there is no "title"
d = dict['description']
k = dict['keyword']
</code></pre>
<p>What if there is an error on line 2, but I want it to continue running the script and assign the ... | 2 | 2009-10-06T08:07:41Z | 1,524,229 | <p>Ever heard of Try Catch and exception handling? You can readup on them <a href="http://docs.python.org/tutorial/errors.html" rel="nofollow">here</a></p>
<p>However, you should shy away from causing errors on purpose, why do you have code that you know will fail? </p>
| 0 | 2009-10-06T08:10:43Z | [
"python"
] |
How to have an error but continue the script in python? | 1,524,216 | <p>Suppose I have this code in Python:</p>
<pre><code>l = dict['link']
t = dict['title'] <<<<<<<<error here, there is no "title"
d = dict['description']
k = dict['keyword']
</code></pre>
<p>What if there is an error on line 2, but I want it to continue running the script and assign the ... | 2 | 2009-10-06T08:07:41Z | 1,524,232 | <p>The easiest option is to use <a href="http://docs.python.org/library/stdtypes.html#dict.get"><code>.get()</code></a>:</p>
<pre><code>l = dict.get('link')
t = dict.get('title')
d = dict.get('description')
k = dict.get('keyword')
</code></pre>
<p>The <code>t</code> variable will then contain <code>None</code> (you c... | 12 | 2009-10-06T08:11:19Z | [
"python"
] |
How to have an error but continue the script in python? | 1,524,216 | <p>Suppose I have this code in Python:</p>
<pre><code>l = dict['link']
t = dict['title'] <<<<<<<<error here, there is no "title"
d = dict['description']
k = dict['keyword']
</code></pre>
<p>What if there is an error on line 2, but I want it to continue running the script and assign the ... | 2 | 2009-10-06T08:07:41Z | 1,524,233 | <pre><code>t = dic.get('title')
</code></pre>
<p>won't produce the error. it's equivalent to:</p>
<pre><code>try:
t = dic['title']
except KeyError:
t = None
</code></pre>
<p>and please don't shadow built-in, don't use <code>dict</code> for a variable name. use something else.</p>
| 8 | 2009-10-06T08:11:26Z | [
"python"
] |
How to have an error but continue the script in python? | 1,524,216 | <p>Suppose I have this code in Python:</p>
<pre><code>l = dict['link']
t = dict['title'] <<<<<<<<error here, there is no "title"
d = dict['description']
k = dict['keyword']
</code></pre>
<p>What if there is an error on line 2, but I want it to continue running the script and assign the ... | 2 | 2009-10-06T08:07:41Z | 1,524,237 | <p>In this case, your best bet is to use</p>
<pre><code>l = dict.get('link', 'default')
t = dict.get('title', 'default')
</code></pre>
<p>etc.</p>
<p>Any values that weren't in the dictionary will be set to <code>'default'</code> (or whatever you choose). Of course, you'll have to deal with this later...</p>
| 1 | 2009-10-06T08:12:16Z | [
"python"
] |
How to have an error but continue the script in python? | 1,524,216 | <p>Suppose I have this code in Python:</p>
<pre><code>l = dict['link']
t = dict['title'] <<<<<<<<error here, there is no "title"
d = dict['description']
k = dict['keyword']
</code></pre>
<p>What if there is an error on line 2, but I want it to continue running the script and assign the ... | 2 | 2009-10-06T08:07:41Z | 1,524,240 | <p>Try/except/finally; see the <a href="http://docs.python.org/tutorial/errors.html" rel="nofollow">tutorial</a></p>
<p>However, the main question is; why are you assigning these to variables in the first place instead of accessing the dictionary?</p>
| 0 | 2009-10-06T08:13:13Z | [
"python"
] |
How to have an error but continue the script in python? | 1,524,216 | <p>Suppose I have this code in Python:</p>
<pre><code>l = dict['link']
t = dict['title'] <<<<<<<<error here, there is no "title"
d = dict['description']
k = dict['keyword']
</code></pre>
<p>What if there is an error on line 2, but I want it to continue running the script and assign the ... | 2 | 2009-10-06T08:07:41Z | 1,524,241 | <p>Use exceptions</p>
<pre><code>try:
l = dict['link']
t = dict['title']
d = dict['description']
k = dict['keyword']
except (RuntimeError, TypeError, NameError):
print ('something')
</code></pre>
| 0 | 2009-10-06T08:13:18Z | [
"python"
] |
How to have an error but continue the script in python? | 1,524,216 | <p>Suppose I have this code in Python:</p>
<pre><code>l = dict['link']
t = dict['title'] <<<<<<<<error here, there is no "title"
d = dict['description']
k = dict['keyword']
</code></pre>
<p>What if there is an error on line 2, but I want it to continue running the script and assign the ... | 2 | 2009-10-06T08:07:41Z | 1,524,770 | <p>If you want a way to consume exceptions and continue (though this is probably not a good idea) you could use a wrapper function such as:</p>
<pre><code>def consume_exception(func, args, exception):
try:
return func(*args)
except exception:
return None
</code></pre>
<p>Or something like that... | 3 | 2009-10-06T10:26:45Z | [
"python"
] |
Why do I get encoding error in python warnings.formatwarning on format string? | 1,524,262 | <p>I get encoding error on this line:</p>
<pre><code>s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message)
</code></pre>
<p>UnicodeEncodeError: 'ascii' codec can't encode character u'\xc4' in position 44: ordinal not in range(128)</p>
<p>I tried to reproduce this error by passing all combinations o... | 5 | 2009-10-06T08:21:07Z | 1,524,278 | <p>One of the operands you are passing is not suitable for ASCII encoding - perhaps it contains either Unicode or Latin-1 characters. Change the format string to Unicode and see what happens.</p>
| 1 | 2009-10-06T08:25:26Z | [
"python",
"encoding",
"warnings"
] |
Why do I get encoding error in python warnings.formatwarning on format string? | 1,524,262 | <p>I get encoding error on this line:</p>
<pre><code>s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message)
</code></pre>
<p>UnicodeEncodeError: 'ascii' codec can't encode character u'\xc4' in position 44: ordinal not in range(128)</p>
<p>I tried to reproduce this error by passing all combinations o... | 5 | 2009-10-06T08:21:07Z | 1,524,374 | <p>This happens when Python tries to coerce an argument:</p>
<pre><code>s = u"\u00fc"
print str(s)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 0: ordinal not in range(128)
</code></pre>
<p>This happens because one of your arguments is an object (not a string of any kind) and Python ca... | 8 | 2009-10-06T08:49:54Z | [
"python",
"encoding",
"warnings"
] |
Why do I get encoding error in python warnings.formatwarning on format string? | 1,524,262 | <p>I get encoding error on this line:</p>
<pre><code>s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message)
</code></pre>
<p>UnicodeEncodeError: 'ascii' codec can't encode character u'\xc4' in position 44: ordinal not in range(128)</p>
<p>I tried to reproduce this error by passing all combinations o... | 5 | 2009-10-06T08:21:07Z | 1,524,465 | <p>You are mixing unicode and str objects. </p>
<p>Explanation:
In Python 2.x, there are two kinds of objects that can contain text strings. str, and unicode. str is a string of bytes, so it can only contain characters between 0 and 255.
Unicode is a string of unicode characters.</p>
<p>You can convert between str an... | 8 | 2009-10-06T09:12:28Z | [
"python",
"encoding",
"warnings"
] |
PyQt context menu | 1,524,349 | <p>I'm adding a contextmenu to a QTableWidget dynamically:</p>
<pre><code>playlistContenxt = QAction("Add to %s" % (currentItem.text()), self.musicTable)
playlistContenxt.setData(currentData)
self.connect(playlistContenxt, SIGNAL("triggered()"), self.addToPlaylistAction)
self.musicTable.addAction(playlistContenxt)
</c... | 2 | 2009-10-06T08:44:15Z | 1,524,385 | <p>You can use <code>QAction.setData</code> to set some data, so that the slot knows which playlist to add to. Then from the slot you can call <code>self.sender()</code> to get the action that triggered the signal, and use <code>action.data()</code> to get the data back.</p>
| 2 | 2009-10-06T08:52:15Z | [
"python",
"qt",
"pyqt4"
] |
PyQt context menu | 1,524,349 | <p>I'm adding a contextmenu to a QTableWidget dynamically:</p>
<pre><code>playlistContenxt = QAction("Add to %s" % (currentItem.text()), self.musicTable)
playlistContenxt.setData(currentData)
self.connect(playlistContenxt, SIGNAL("triggered()"), self.addToPlaylistAction)
self.musicTable.addAction(playlistContenxt)
</c... | 2 | 2009-10-06T08:44:15Z | 1,525,572 | <p>The correct way is to use <a href="http://doc.trolltech.com/4.5/qsignalmapper.html#details" rel="nofollow">signal mapper</a>: You can assign data to each of the senders and get a signal with that data.</p>
| 4 | 2009-10-06T13:24:40Z | [
"python",
"qt",
"pyqt4"
] |
Is an applet a proper solution for hardware detection and driver install? | 1,524,606 | <p>Can I use applets to inform me which hardware is installed on client system (fingerprint reader)? And if it is installed, can it tell me its version, so that it can download the proper plugin from a site? So that after everything is OK, the user can use his fingerprint reader to authenticate himself?</p>
| 0 | 2009-10-06T09:45:53Z | 1,524,622 | <p>Applet should be better if your application is not depended on IE.
If for IE only then use COM/ActiveX</p>
| 0 | 2009-10-06T09:50:28Z | [
"c#",
"python",
"ruby"
] |
How do I display images at different times on webpage | 1,524,713 | <p>I'm supposed to display images at certain times of the day on the webpage, Please can anyone tell me how to go about it</p>
| 1 | 2009-10-06T10:15:14Z | 1,524,724 | <p>You could make a Date object in javascript. Check the current time and depending on the time, you set the img src to whatever image you want for that time of day :) or hide the image through myimg.style.visibility = "hidden" if you dont want to display an image at that moment.</p>
| 0 | 2009-10-06T10:17:55Z | [
"python",
"django"
] |
How do I display images at different times on webpage | 1,524,713 | <p>I'm supposed to display images at certain times of the day on the webpage, Please can anyone tell me how to go about it</p>
| 1 | 2009-10-06T10:15:14Z | 1,524,740 | <p>The safest way is to do this on the server side, do not do this on the client side using javascript because clients may have different timezones.</p>
<p>for instance in PHP:</p>
<pre><code><style type="text/css"> #someimage{ position:absolute;left:200px;top:100px; }</style>
<?php
$h = intval(d... | 1 | 2009-10-06T10:21:02Z | [
"python",
"django"
] |
How do I display images at different times on webpage | 1,524,713 | <p>I'm supposed to display images at certain times of the day on the webpage, Please can anyone tell me how to go about it</p>
| 1 | 2009-10-06T10:15:14Z | 1,524,793 | <p>You'll need a template tag which checks the time of day and outputs the relevant HTML. How you do that depends on how you want to determine which image is for what time of day. For example, you could have a model which records a change_time and an image path, and the tag would get the image with the most recent chan... | 2 | 2009-10-06T10:31:35Z | [
"python",
"django"
] |
How do I display images at different times on webpage | 1,524,713 | <p>I'm supposed to display images at certain times of the day on the webpage, Please can anyone tell me how to go about it</p>
| 1 | 2009-10-06T10:15:14Z | 1,524,812 | <p>If you need to change the image before a page refresh, you could use jquery ajax call to get the correct image. jquery has some interval functionality which would allow this.</p>
| 0 | 2009-10-06T10:36:21Z | [
"python",
"django"
] |
How to fix encoding in Python Mechanize? | 1,525,295 | <p>here is the sample code:</p>
<pre><code>from mechanize import Browser
br = Browser()
page = br.open('http://hunters.tclans.ru/news.php?readmore=2')
br.form = br.forms().next()
print br.form
</code></pre>
<p>The problem is that server return incorrect encoding (windows-cp1251). How can I manually set the encoding ... | 5 | 2009-10-06T12:26:01Z | 1,525,660 | <p>I don't know about Mechanize, but you could hack <code>codecs</code> to accept wrong encoding names that have both âwindowsâ <em>and</em> âcpâ:</p>
<pre><code>>>> def fixcp(name):
... if name.lower().startswith('windows-cp'):
... try:
... return codecs.lookup(name[:8]+name[1... | 3 | 2009-10-06T13:39:27Z | [
"python",
"encoding",
"mechanize"
] |
How to fix encoding in Python Mechanize? | 1,525,295 | <p>here is the sample code:</p>
<pre><code>from mechanize import Browser
br = Browser()
page = br.open('http://hunters.tclans.ru/news.php?readmore=2')
br.form = br.forms().next()
print br.form
</code></pre>
<p>The problem is that server return incorrect encoding (windows-cp1251). How can I manually set the encoding ... | 5 | 2009-10-06T12:26:01Z | 1,525,786 | <p>Fixed by setting</p>
<pre><code>br._factory.encoding = enc
br._factory._forms_factory.encoding = enc
br._factory._links_factory._encoding = enc
</code></pre>
<p>(note the underscores) after br.open()</p>
| 2 | 2009-10-06T14:00:47Z | [
"python",
"encoding",
"mechanize"
] |
Python: smarter way to calculate loan payments | 1,525,611 | <p>How to calculate the monthly fee on a loan?</p>
<p>Given is:</p>
<ul>
<li>a: an amount to loan.</li>
<li>b: the loan period (number of months).</li>
<li>c: the interest rate p.a. (interests is calculated and added every month, 1/12 of the interest is added. So if the interest is on 12%, 1% interest is added every ... | 6 | 2009-10-06T13:30:59Z | 1,525,676 | <p>You can keep paying the interest of every month; then, you will alway owe the same amont.</p>
<pre><code>Owe_1 = a
Int_2 = Owe_1*(InterestRate/12)
Pay_2 = Int_2
Owe_2 = Owe_1 + Int_2 - Pay_2 # ==> Owe_1 + Int_2 - Int_2 = Owe_1
Int_3 = Owe_2*(InterestRate/12)
Pay_3 = Int_3
Owe_3 = Owe_2 + Int_3 - Pay_3 # ==>... | 0 | 2009-10-06T13:43:17Z | [
"python",
"algorithm",
"math",
"finance"
] |
Python: smarter way to calculate loan payments | 1,525,611 | <p>How to calculate the monthly fee on a loan?</p>
<p>Given is:</p>
<ul>
<li>a: an amount to loan.</li>
<li>b: the loan period (number of months).</li>
<li>c: the interest rate p.a. (interests is calculated and added every month, 1/12 of the interest is added. So if the interest is on 12%, 1% interest is added every ... | 6 | 2009-10-06T13:30:59Z | 1,525,757 | <p>Perhaps the easiest way to think about this is to split the loan in two parts, one part which is to be repaid in full and another part where you don't pay off anything. You have already computed the monthly fee for the first part.</p>
| 4 | 2009-10-06T13:56:27Z | [
"python",
"algorithm",
"math",
"finance"
] |
Python: smarter way to calculate loan payments | 1,525,611 | <p>How to calculate the monthly fee on a loan?</p>
<p>Given is:</p>
<ul>
<li>a: an amount to loan.</li>
<li>b: the loan period (number of months).</li>
<li>c: the interest rate p.a. (interests is calculated and added every month, 1/12 of the interest is added. So if the interest is on 12%, 1% interest is added every ... | 6 | 2009-10-06T13:30:59Z | 1,525,889 | <p>This is a basically a <a href="http://en.wikipedia.org/wiki/Mortgage%5Fcalculator">mortgage repayment calculation</a>. </p>
<p>Assuming that start is greater than end, and that interest is between 0 and 1 (i.e. 0.1 for 10% interest)</p>
<p>First consider the part of the payment you want to pay off.</p>
<pre><code... | 7 | 2009-10-06T14:22:32Z | [
"python",
"algorithm",
"math",
"finance"
] |
Python: smarter way to calculate loan payments | 1,525,611 | <p>How to calculate the monthly fee on a loan?</p>
<p>Given is:</p>
<ul>
<li>a: an amount to loan.</li>
<li>b: the loan period (number of months).</li>
<li>c: the interest rate p.a. (interests is calculated and added every month, 1/12 of the interest is added. So if the interest is on 12%, 1% interest is added every ... | 6 | 2009-10-06T13:30:59Z | 31,782,045 | <p><strong>python code to calculate emi</strong></p>
<pre><code>class EMI_CALCULATOR(object):
# Data attributes
# Helps to calculate EMI
Loan_amount = None # assigning none values
Month_Payment = None # assigning none values
Interest_rate = None #assigning none values
Payment_period = None #assigning none v... | 0 | 2015-08-03T07:50:20Z | [
"python",
"algorithm",
"math",
"finance"
] |
Python: smarter way to calculate loan payments | 1,525,611 | <p>How to calculate the monthly fee on a loan?</p>
<p>Given is:</p>
<ul>
<li>a: an amount to loan.</li>
<li>b: the loan period (number of months).</li>
<li>c: the interest rate p.a. (interests is calculated and added every month, 1/12 of the interest is added. So if the interest is on 12%, 1% interest is added every ... | 6 | 2009-10-06T13:30:59Z | 35,393,533 | <p>This rather a detailed way but will give the whole payment as well</p>
<pre><code># Mortgage Loan that gives the balance and total payment per year
# Function that gives the monthly payment
def f1 (principle,annual_interest_rate,duration):
r = annual_interest_rate/1200
n = duration*12
a=principle*r*((1... | 0 | 2016-02-14T15:35:00Z | [
"python",
"algorithm",
"math",
"finance"
] |
Creating files on AppEngine | 1,525,625 | <p>I'm trying to store some data in a binary file:</p>
<pre><code>import os, pickle
o = some_object()
file = open('test', 'wb') #this causes the error
pickle.dump(o, file)
file.close()
</code></pre>
<p>I get this error: <strong>IOError: invalid mode: wb</strong></p>
<p>It doesn't work (neither on test server or GAE... | 0 | 2009-10-06T13:33:56Z | 1,525,638 | <p>I think the short answer is you shouldn't. I suggest you store this info in BigTable as a Blob and serve it up that way.</p>
| 1 | 2009-10-06T13:35:32Z | [
"python",
"google-app-engine",
"file",
"io"
] |
Creating files on AppEngine | 1,525,625 | <p>I'm trying to store some data in a binary file:</p>
<pre><code>import os, pickle
o = some_object()
file = open('test', 'wb') #this causes the error
pickle.dump(o, file)
file.close()
</code></pre>
<p>I get this error: <strong>IOError: invalid mode: wb</strong></p>
<p>It doesn't work (neither on test server or GAE... | 0 | 2009-10-06T13:33:56Z | 1,525,639 | <p>GAE is readonly, you can only store stuff in the datastore</p>
<p><a href="http://code.google.com/appengine/docs/python/runtime.html#The%5FSandbox" rel="nofollow">here is a link to the docs</a></p>
| 5 | 2009-10-06T13:35:33Z | [
"python",
"google-app-engine",
"file",
"io"
] |
Python, subprocess, devenv, why no output? | 1,525,696 | <p>I build a Visual Studio solution from a Python script. Everything works nicely, except that I am unable to capture the build output.</p>
<pre><code>p = subprocess.Popen(['devenv', 'solution.sln', '/build'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate()
ret = p.returncode
</code></pre>... | 6 | 2009-10-06T13:46:06Z | 1,525,720 | <p>That's probably because the software you're running doesn't write to <code>stdout</code> or <code>stderr</code>. Maybe it <a href="http://msdn.microsoft.com/en-us/library/ms687403%28VS.85%29.aspx" rel="nofollow">writes directly to the terminal/console</a>.</p>
<p>If that's the case you'll need some <a href="http://... | 0 | 2009-10-06T13:50:32Z | [
"python",
"subprocess"
] |
Python, subprocess, devenv, why no output? | 1,525,696 | <p>I build a Visual Studio solution from a Python script. Everything works nicely, except that I am unable to capture the build output.</p>
<pre><code>p = subprocess.Popen(['devenv', 'solution.sln', '/build'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate()
ret = p.returncode
</code></pre>... | 6 | 2009-10-06T13:46:06Z | 1,525,773 | <p>You should build the solution with <code>msbuild.exe</code> instead, which is designed to give feedback to stdout and stderr. <code>msbuild.exe</code> is located at</p>
<p><code>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\msbuild.exe</code> (to build a VS2005 solution)
or <code>C:\WINDOWS\Microsoft.NET\Framework\... | 2 | 2009-10-06T13:58:48Z | [
"python",
"subprocess"
] |
Python, subprocess, devenv, why no output? | 1,525,696 | <p>I build a Visual Studio solution from a Python script. Everything works nicely, except that I am unable to capture the build output.</p>
<pre><code>p = subprocess.Popen(['devenv', 'solution.sln', '/build'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate()
ret = p.returncode
</code></pre>... | 6 | 2009-10-06T13:46:06Z | 1,525,775 | <p>Probably your problem is the same that the pipe's buffer fills up. Check <a href="http://stackoverflow.com/questions/1445627/how-can-i-find-out-why-subprocess-popen-wait-waits-forever-if-stdoutpipe">this question</a> for a good answer.</p>
| -2 | 2009-10-06T13:59:09Z | [
"python",
"subprocess"
] |
Python, subprocess, devenv, why no output? | 1,525,696 | <p>I build a Visual Studio solution from a Python script. Everything works nicely, except that I am unable to capture the build output.</p>
<pre><code>p = subprocess.Popen(['devenv', 'solution.sln', '/build'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate()
ret = p.returncode
</code></pre>... | 6 | 2009-10-06T13:46:06Z | 1,646,191 | <p>Change it from 'devenv' to 'devenv.com'. Apparenty Popen looks for .EXEs first but the shell looks for .COMs first. Switching to 'devenv.com' worked for me.</p>
<p>devenv is significantly faster then msbuild for incremental builds. I just did a build with an up to date project, meaning nothing should happen.</p>
... | 24 | 2009-10-29T19:59:25Z | [
"python",
"subprocess"
] |
creating a .mat file from python | 1,526,002 | <p>I have a variable <code>exon = [[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10]]]</code>. I would like to create a mat file like the following </p>
<pre><code>>>
exon : [3*2 double] [2*2 double]
</code></pre>
<p>When I used the python code to do the same it is showing error message. here is my python code</p>
... | 1 | 2009-10-06T14:38:51Z | 1,526,549 | <p>Sage is an open source mathematics software which aims at bundling together the python syntax and the python interpreter with other tools like Matlab, Octave, Mathematica, etc...</p>
<p>Maybe you want to have a look at it:</p>
<ul>
<li><a href="http://www.sagemath.org/doc/tutorial/index.html" rel="nofollow">http:/... | 1 | 2009-10-06T16:02:39Z | [
"python",
"scipy",
"mat-file"
] |
creating a .mat file from python | 1,526,002 | <p>I have a variable <code>exon = [[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10]]]</code>. I would like to create a mat file like the following </p>
<pre><code>>>
exon : [3*2 double] [2*2 double]
</code></pre>
<p>When I used the python code to do the same it is showing error message. here is my python code</p>
... | 1 | 2009-10-06T14:38:51Z | 1,644,090 | <p>You seem to want two different arrays linked to same variable name in Matlab. That is not possible. In MATLAB you can have cell arrays, or structs, which contain other arrays, but you cannot have just a tuple of arrays assigned to a single variable (which is what you have in mdict={'exon': (exon[0], exon<a href="htt... | 6 | 2009-10-29T14:22:37Z | [
"python",
"scipy",
"mat-file"
] |
Sort string collection in Python using various locale settings | 1,526,109 | <p>I want to sort list of strings with respect to user language preference. I have a multilanguage Python webapp and what is the correct way to sort strings such way?</p>
<p>I know I can set up locale, like this:</p>
<pre><code>import locale
locale.setlocale(locale.LC_ALL, '')
</code></pre>
<p>But this should be do... | 4 | 2009-10-06T14:54:05Z | 1,526,525 | <p>Given the documentation warnings, it seems you are on your own if you try to set locale diffrently in different threads.</p>
<p>If you can split your problem into one thread per locale, might you not as well split it into one subprocess per locale, using Python 2.6's multiprocessing?</p>
<p>It seems everything sol... | 0 | 2009-10-06T15:57:48Z | [
"python",
"google-app-engine",
"sorting",
"web-applications",
"collation"
] |
Sort string collection in Python using various locale settings | 1,526,109 | <p>I want to sort list of strings with respect to user language preference. I have a multilanguage Python webapp and what is the correct way to sort strings such way?</p>
<p>I know I can set up locale, like this:</p>
<pre><code>import locale
locale.setlocale(locale.LC_ALL, '')
</code></pre>
<p>But this should be do... | 4 | 2009-10-06T14:54:05Z | 1,527,075 | <p>I would recommend <a href="http://pyicu.osafoundation.org/" rel="nofollow">pyICU</a> -- Python bindings for IBM's rich open-source <a href="http://www-01.ibm.com/software/globalization/icu/index.jsp" rel="nofollow">ICU</a> internationalization library. You make a Collator object e.g. with:</p>
<pre><code> colla... | 4 | 2009-10-06T17:50:30Z | [
"python",
"google-app-engine",
"sorting",
"web-applications",
"collation"
] |
Sort string collection in Python using various locale settings | 1,526,109 | <p>I want to sort list of strings with respect to user language preference. I have a multilanguage Python webapp and what is the correct way to sort strings such way?</p>
<p>I know I can set up locale, like this:</p>
<pre><code>import locale
locale.setlocale(locale.LC_ALL, '')
</code></pre>
<p>But this should be do... | 4 | 2009-10-06T14:54:05Z | 1,539,883 | <p>You will want the latest possible ICU under your pyICU to get the best and most up to date data.</p>
| 1 | 2009-10-08T19:18:36Z | [
"python",
"google-app-engine",
"sorting",
"web-applications",
"collation"
] |
Sort string collection in Python using various locale settings | 1,526,109 | <p>I want to sort list of strings with respect to user language preference. I have a multilanguage Python webapp and what is the correct way to sort strings such way?</p>
<p>I know I can set up locale, like this:</p>
<pre><code>import locale
locale.setlocale(locale.LC_ALL, '')
</code></pre>
<p>But this should be do... | 4 | 2009-10-06T14:54:05Z | 1,542,568 | <p>Another possible solution is to use SQL server that has good locale support (unfortunately, sqlite is not an option). Then I can put all data to temporary memory table and SELECT them with ORDER BY. IMO it should be better solution than trying to distribute locale settings to multiple processes as kaizer.se's answer... | 0 | 2009-10-09T08:29:49Z | [
"python",
"google-app-engine",
"sorting",
"web-applications",
"collation"
] |
Operations for Long and Float in Python | 1,526,142 | <p>I'm trying to compute this:</p>
<pre><code>from scipy import *
3600**3400 * (exp(-3600)) / factorial(3400)
</code></pre>
<p>the error: unsupported long and float</p>
| 0 | 2009-10-06T14:57:49Z | 1,526,366 | <p>Well the error is coming about because you are trying to multiply</p>
<pre><code>3600**3400
</code></pre>
<p>which is a long with </p>
<pre><code>exp(-3600)
</code></pre>
<p>which is a float. </p>
<p>But regardless, the error you are receiving is disguising the true problem. It seems exp(-3600) is too big a num... | 0 | 2009-10-06T15:31:18Z | [
"python",
"floating-point",
"scipy",
"long-integer"
] |
Operations for Long and Float in Python | 1,526,142 | <p>I'm trying to compute this:</p>
<pre><code>from scipy import *
3600**3400 * (exp(-3600)) / factorial(3400)
</code></pre>
<p>the error: unsupported long and float</p>
| 0 | 2009-10-06T14:57:49Z | 1,526,443 | <p>Try using logarithms instead of working with the numbers directly. Since none of your operations are addition or subtraction, you could do the whole thing in logarithm form and convert back at the end.</p>
| 3 | 2009-10-06T15:44:22Z | [
"python",
"floating-point",
"scipy",
"long-integer"
] |
Operations for Long and Float in Python | 1,526,142 | <p>I'm trying to compute this:</p>
<pre><code>from scipy import *
3600**3400 * (exp(-3600)) / factorial(3400)
</code></pre>
<p>the error: unsupported long and float</p>
| 0 | 2009-10-06T14:57:49Z | 1,526,501 | <p>You could try using the <a href="http://docs.python.org/library/decimal.html" rel="nofollow">Decimal</a> object. Calculations will be slower but you won't have trouble with really small numbers.</p>
<pre><code>from decimal import Decimal
</code></pre>
<p>I don't know how Decimal interacts with the scipy module, h... | 1 | 2009-10-06T15:53:16Z | [
"python",
"floating-point",
"scipy",
"long-integer"
] |
Operations for Long and Float in Python | 1,526,142 | <p>I'm trying to compute this:</p>
<pre><code>from scipy import *
3600**3400 * (exp(-3600)) / factorial(3400)
</code></pre>
<p>the error: unsupported long and float</p>
| 0 | 2009-10-06T14:57:49Z | 1,527,121 | <p>Computing with numbers of such magnitude, you just can't use ordinary 64-bit-or-so floats, which is what Python's core runtime supports. Consider <a href="http://code.google.com/p/gmpy/" rel="nofollow"><code>gmpy</code></a> (do <strong>not</strong> get the sourceforge version, it's aeons out of date) -- with that, ... | 2 | 2009-10-06T17:58:45Z | [
"python",
"floating-point",
"scipy",
"long-integer"
] |
Operations for Long and Float in Python | 1,526,142 | <p>I'm trying to compute this:</p>
<pre><code>from scipy import *
3600**3400 * (exp(-3600)) / factorial(3400)
</code></pre>
<p>the error: unsupported long and float</p>
| 0 | 2009-10-06T14:57:49Z | 1,528,704 | <p>exp(-3600) is too smale, factorial(3400) is too large: </p>
<pre><code>In [1]: from scipy import exp
In [2]: exp(-3600)
Out[2]: 0.0
In [3]: from scipy import factorial
In [4]: factorial(3400)
Out[4]: array(1.#INF)
</code></pre>
<p>What about calculate it step by step as a workaround(and it makes sense
to check... | 0 | 2009-10-06T23:40:17Z | [
"python",
"floating-point",
"scipy",
"long-integer"
] |
Formatting date string in Python for dates prior to 1900? | 1,526,170 | <p>Can anyone explain the best way to format a date time string in Python where the date value is prior to the year 1900? <code>strftime</code> requires dates later than 1900.</p>
| 3 | 2009-10-06T15:03:08Z | 1,526,249 | <p>It's a bit cumbersome, but it works (at least in stable versions of python):</p>
<pre><code>>>> ts = datetime.datetime(1895, 10, 6, 16, 4, 5)
>>> '{0.year}-{0.month:{1}}-{0.day:{1}} {0.hour:{1}}:{0.minute:{1}}'.format(ts, '02')
'1895-10-06 16:04'
</code></pre>
<p>note that <code>str</code> would ... | 3 | 2009-10-06T15:14:44Z | [
"python",
"datetime"
] |
Formatting date string in Python for dates prior to 1900? | 1,526,170 | <p>Can anyone explain the best way to format a date time string in Python where the date value is prior to the year 1900? <code>strftime</code> requires dates later than 1900.</p>
| 3 | 2009-10-06T15:03:08Z | 1,526,751 | <p>The <code>babel</code> internationalization library seems to have no problems with it. See the <a href="http://babel.edgewall.org/wiki/Documentation/0.9/dates.html" rel="nofollow">docs</a> for <code>babel.dates</code></p>
| 1 | 2009-10-06T16:43:32Z | [
"python",
"datetime"
] |
Formatting date string in Python for dates prior to 1900? | 1,526,170 | <p>Can anyone explain the best way to format a date time string in Python where the date value is prior to the year 1900? <code>strftime</code> requires dates later than 1900.</p>
| 3 | 2009-10-06T15:03:08Z | 1,527,779 | <p>The calendar is exactly the same every 400 years. Therefore it is sufficient to change year by multiple of 400 such as <code>year >= 1900</code> before calling <code>datetime.strftime()</code>.</p>
<p>The code shows what problems such approach has:</p>
<pre><code>#/usr/bin/env python2.6
import re
import warning... | 1 | 2009-10-06T20:01:59Z | [
"python",
"datetime"
] |
How do I memoize expensive calculations on Django model objects? | 1,526,191 | <p>I have several TextField columns on my UserProfile object which contain JSON objects. I've also defined a setter/getter property for each column which encapsulates the logic for serializing and deserializing the JSON into python datastructures.</p>
<p>The nature of this data ensures that it will be accessed many ti... | 9 | 2009-10-06T15:06:48Z | 1,526,245 | <p>Generally, I use a pattern like this:</p>
<pre><code>def get_expensive_operation(self):
if not hasattr(self, '_expensive_operation'):
self._expensive_operation = self.expensive_operation()
return self._expensive_operation
</code></pre>
<p>Then you use the <code>get_expensive_operation</code> method... | 16 | 2009-10-06T15:14:27Z | [
"python",
"django",
"django-models",
"memoization"
] |
How do I memoize expensive calculations on Django model objects? | 1,526,191 | <p>I have several TextField columns on my UserProfile object which contain JSON objects. I've also defined a setter/getter property for each column which encapsulates the logic for serializing and deserializing the JSON into python datastructures.</p>
<p>The nature of this data ensures that it will be accessed many ti... | 9 | 2009-10-06T15:06:48Z | 2,634,701 | <p>You may be interested in a built-in django decorator <code>django.utils.functional.memoize</code>.</p>
<p>Django uses this to cache expensive operation like url resolving.</p>
| 22 | 2010-04-14T03:28:16Z | [
"python",
"django",
"django-models",
"memoization"
] |
Extracting data from a CSV file in Python | 1,526,607 | <p>I just got my data and it is given to me as a <code>csv</code> file.</p>
<p>It looks like this in data studio(where the file was taken).</p>
<pre><code>Counts frequency
300 1
302 5
303 7
</code></pre>
<p>Excel can't handle the computations so that's why I'm trying to load it in python(it has <code>sc... | 0 | 2009-10-06T16:16:27Z | 1,526,618 | <p>Use the Python <a href="http://docs.python.org/library/csv" rel="nofollow">csv</a> module.</p>
| 9 | 2009-10-06T16:18:31Z | [
"python",
"csv"
] |
Extracting data from a CSV file in Python | 1,526,607 | <p>I just got my data and it is given to me as a <code>csv</code> file.</p>
<p>It looks like this in data studio(where the file was taken).</p>
<pre><code>Counts frequency
300 1
302 5
303 7
</code></pre>
<p>Excel can't handle the computations so that's why I'm trying to load it in python(it has <code>sc... | 0 | 2009-10-06T16:16:27Z | 1,526,773 | <pre><code>import csv
counts = []
frequencies = []
for d in csv.DictReader(open('yourfile.csv'), delimiter='\t'):
counts.append(int(d['Counts']))
frequencies.append(int(d['frequency']))
print 'Counts = ', counts
print 'frequency = ', frequencies
</code></pre>
| 6 | 2009-10-06T16:47:09Z | [
"python",
"csv"
] |
How to deal with query parameter's encoding? | 1,526,965 | <p>I assumed that any data being sent to my parameter strings would be utf-8, since that is what my whole site uses throughout. Lo-and-behold I was wrong.</p>
<p>For <a href="http://metaward.com/alias/add?alias=eu.wowarmory.com%2Fcharacter-sheet.xml%3Fr%3DDer%20Rat%20von%20Dalaran%26cn%3DB%C3%A4ule" rel="nofollow">thi... | 3 | 2009-10-06T17:27:51Z | 1,527,018 | <p>Although it's AFAIK not specified anywhere, all browsers use the character encoding of the HTML page, on which the form is embedded as the encoding for submitting the form back to the server. So if you want the URL parameters to be UTF-8-encoded, you have to make sure that the HTML page, on which the form is embedde... | 0 | 2009-10-06T17:38:32Z | [
"python",
"django",
"unicode",
"utf-8"
] |
How to deal with query parameter's encoding? | 1,526,965 | <p>I assumed that any data being sent to my parameter strings would be utf-8, since that is what my whole site uses throughout. Lo-and-behold I was wrong.</p>
<p>For <a href="http://metaward.com/alias/add?alias=eu.wowarmory.com%2Fcharacter-sheet.xml%3Fr%3DDer%20Rat%20von%20Dalaran%26cn%3DB%C3%A4ule" rel="nofollow">thi... | 3 | 2009-10-06T17:27:51Z | 1,527,024 | <p>According to <a href="http://stackoverflow.com/questions/544071/get-non-utf-8-form-fields-as-utf-8-in-php">http://stackoverflow.com/questions/544071/get-non-utf-8-form-fields-as-utf-8-in-php</a>, you'll need to make sure the page itself is served up using UTF8 encoding. </p>
| 0 | 2009-10-06T17:39:52Z | [
"python",
"django",
"unicode",
"utf-8"
] |
How to deal with query parameter's encoding? | 1,526,965 | <p>I assumed that any data being sent to my parameter strings would be utf-8, since that is what my whole site uses throughout. Lo-and-behold I was wrong.</p>
<p>For <a href="http://metaward.com/alias/add?alias=eu.wowarmory.com%2Fcharacter-sheet.xml%3Fr%3DDer%20Rat%20von%20Dalaran%26cn%3DB%C3%A4ule" rel="nofollow">thi... | 3 | 2009-10-06T17:27:51Z | 1,539,789 | <p>Since Django 1.0 all values you get from form submission are unicode objects, not bytestrings like in Django 0.96 and earlier. To get utf-8 from your values encode them with utf-8 codec:</p>
<pre><code>request.POST['somefield'].encode('utf-8')
</code></pre>
<p>To get query parameters decoded properly, they have to... | 3 | 2009-10-08T18:59:36Z | [
"python",
"django",
"unicode",
"utf-8"
] |
How to deal with query parameter's encoding? | 1,526,965 | <p>I assumed that any data being sent to my parameter strings would be utf-8, since that is what my whole site uses throughout. Lo-and-behold I was wrong.</p>
<p>For <a href="http://metaward.com/alias/add?alias=eu.wowarmory.com%2Fcharacter-sheet.xml%3Fr%3DDer%20Rat%20von%20Dalaran%26cn%3DB%C3%A4ule" rel="nofollow">thi... | 3 | 2009-10-06T17:27:51Z | 1,592,932 | <p>You should also add <code>accept-charset="UTF-8"</code> to the <code><form/></code> tag.</p>
| 1 | 2009-10-20T07:07:55Z | [
"python",
"django",
"unicode",
"utf-8"
] |
How to deal with query parameter's encoding? | 1,526,965 | <p>I assumed that any data being sent to my parameter strings would be utf-8, since that is what my whole site uses throughout. Lo-and-behold I was wrong.</p>
<p>For <a href="http://metaward.com/alias/add?alias=eu.wowarmory.com%2Fcharacter-sheet.xml%3Fr%3DDer%20Rat%20von%20Dalaran%26cn%3DB%C3%A4ule" rel="nofollow">thi... | 3 | 2009-10-06T17:27:51Z | 1,673,377 | <p>Getting an utf-8 string from the submitted form should just be a matter of encoding the
unicode object:</p>
<p>next = request.POST['next'].encode('utf-8')</p>
<p>For the AJAX request, can you confirm that that request is also being sent as utf-8 and declared as utf-8 in the headers?</p>
| 0 | 2009-11-04T12:04:37Z | [
"python",
"django",
"unicode",
"utf-8"
] |
I'm trying to figure out how to get python to simply post the lyrics to a song | 1,527,097 | <p><strong>I'm a beginner in python programming and on one of my assignments I am to use python to write a code that will say these lyrics.</strong></p>
<p>This old man, he played one<br />
He played knick-knack on my thumb<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
... | 0 | 2009-10-06T17:53:17Z | 1,527,128 | <p>Hint: You will need to use a loop</p>
<p>I would look at the <a href="http://docs.python.org/tutorial/controlflow.html" rel="nofollow">Python Flow Control</a> documentation. Also note the <code>range()</code> function.</p>
<p>You can grab the <em>n</em>'th element from an array like this:</p>
<pre><code>val = som... | 5 | 2009-10-06T17:59:40Z | [
"python"
] |
I'm trying to figure out how to get python to simply post the lyrics to a song | 1,527,097 | <p><strong>I'm a beginner in python programming and on one of my assignments I am to use python to write a code that will say these lyrics.</strong></p>
<p>This old man, he played one<br />
He played knick-knack on my thumb<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
... | 0 | 2009-10-06T17:53:17Z | 1,527,133 | <p>I am not sure if I want to do your homework, but I will give you some hints: To me, this looks like a good place for a for loop. Use range, xrange, or enumerate.</p>
| 0 | 2009-10-06T18:00:26Z | [
"python"
] |
I'm trying to figure out how to get python to simply post the lyrics to a song | 1,527,097 | <p><strong>I'm a beginner in python programming and on one of my assignments I am to use python to write a code that will say these lyrics.</strong></p>
<p>This old man, he played one<br />
He played knick-knack on my thumb<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
... | 0 | 2009-10-06T17:53:17Z | 1,527,152 | <p>First, you probably want to say <code>z = 0</code> because arrays in Python (and most programming languages) are zero-indexed - the first element of <code>num</code> is <code>num[0]</code>, the second is <code>num[1]</code>, and so on. Though we don't really even need <code>z</code>. More on that later.</p>
<p>Seco... | 0 | 2009-10-06T18:03:05Z | [
"python"
] |
I'm trying to figure out how to get python to simply post the lyrics to a song | 1,527,097 | <p><strong>I'm a beginner in python programming and on one of my assignments I am to use python to write a code that will say these lyrics.</strong></p>
<p>This old man, he played one<br />
He played knick-knack on my thumb<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
... | 0 | 2009-10-06T17:53:17Z | 1,527,235 | <p>Your rhyme encourages violence against the Irish. Nevertheless, here's some help. </p>
<p>Since the rhymes themselves have two parts, I've put each rhyme as a two part list, put together into a list of all those rhymes. </p>
<pre><code># List of rhymes, with each part of the rhyme as another list.
rhymes = ['one',... | 0 | 2009-10-06T18:22:32Z | [
"python"
] |
I'm trying to figure out how to get python to simply post the lyrics to a song | 1,527,097 | <p><strong>I'm a beginner in python programming and on one of my assignments I am to use python to write a code that will say these lyrics.</strong></p>
<p>This old man, he played one<br />
He played knick-knack on my thumb<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
... | 0 | 2009-10-06T17:53:17Z | 1,527,279 | <p>first half shamelessly copied from from nailer's answer:</p>
<pre><code># List of rhymes, with each part of the rhyme as another list.
rhymes = ['one','on my thumb'],['two','on my shoe']
for number, position in rhymes:
# print your output in terms of number and position
</code></pre>
| 0 | 2009-10-06T18:29:00Z | [
"python"
] |
I'm trying to figure out how to get python to simply post the lyrics to a song | 1,527,097 | <p><strong>I'm a beginner in python programming and on one of my assignments I am to use python to write a code that will say these lyrics.</strong></p>
<p>This old man, he played one<br />
He played knick-knack on my thumb<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
... | 0 | 2009-10-06T17:53:17Z | 1,527,284 | <p>There is in fact a more Pythonic answer to your homework. Again, I can't give it to you directly, but as well as looking at the <a href="http://docs.python.org/tutorial/controlflow.html" rel="nofollow">loop documentation</a>, you might also want to look at <a href="http://docs.python.org/library/functions.html?high... | 2 | 2009-10-06T18:29:44Z | [
"python"
] |
I'm trying to figure out how to get python to simply post the lyrics to a song | 1,527,097 | <p><strong>I'm a beginner in python programming and on one of my assignments I am to use python to write a code that will say these lyrics.</strong></p>
<p>This old man, he played one<br />
He played knick-knack on my thumb<br />
Knick-knack paddywhack, give your dog a bone<br />
This old man came rolling home </p>
... | 0 | 2009-10-06T17:53:17Z | 1,527,390 | <p>First, read up on tuples and lists in Python; then read up on the for loop.</p>
<p>I suggest that you use a tuple to store things that go together.</p>
<pre><code># define a list of tuples
lst = [ ("eggs", "an omelet"), ("bread", "a sandwich"), ("sugar", "cookies") ]
for ingredient, food in lst:
print "I need... | 2 | 2009-10-06T18:55:20Z | [
"python"
] |
Python 3.1 RSS Parser? | 1,527,230 | <p>Anyone know of a good feed parser for python 3.1?
I was using feedparser for 2.5 but it doesn't seem to be ported to 3.1 yet, and it's apparently more complicated than just running 2to3.py on it.
Any help?</p>
| 8 | 2009-10-06T18:21:12Z | 1,568,072 | <p>You may take a look at the <a href="http://blog.ianbicking.org/2007/08/02/atom-models/" rel="nofollow">Atom Models</a> blog post by Ian Bicking. He proposes not to use any special "feed parsing" library because Atom and RSS are <strong>just XML</strong> so your model is really an XML tree, not some fancy class. You ... | 4 | 2009-10-14T18:17:43Z | [
"python",
"rss",
"python-3.x",
"feeds"
] |
Python 3.1 RSS Parser? | 1,527,230 | <p>Anyone know of a good feed parser for python 3.1?
I was using feedparser for 2.5 but it doesn't seem to be ported to 3.1 yet, and it's apparently more complicated than just running 2to3.py on it.
Any help?</p>
| 8 | 2009-10-06T18:21:12Z | 1,568,128 | <p>Start porting <code>feedparser</code> to Python 3.1.</p>
| 0 | 2009-10-14T18:27:52Z | [
"python",
"rss",
"python-3.x",
"feeds"
] |
Python 3.1 RSS Parser? | 1,527,230 | <p>Anyone know of a good feed parser for python 3.1?
I was using feedparser for 2.5 but it doesn't seem to be ported to 3.1 yet, and it's apparently more complicated than just running 2to3.py on it.
Any help?</p>
| 8 | 2009-10-06T18:21:12Z | 4,282,679 | <p>I've been working on porting feedparser to Python 3, and I've published <a href="https://github.com/kurtmckee/feedparser/tree/py3/" rel="nofollow">a feedparser/Python 3 development branch</a> at GitHub with the results of that work so far.</p>
<p>There is also an open bug report about porting feedparser to Python 3... | 1 | 2010-11-26T05:12:43Z | [
"python",
"rss",
"python-3.x",
"feeds"
] |
Python 3.1 RSS Parser? | 1,527,230 | <p>Anyone know of a good feed parser for python 3.1?
I was using feedparser for 2.5 but it doesn't seem to be ported to 3.1 yet, and it's apparently more complicated than just running 2to3.py on it.
Any help?</p>
| 8 | 2009-10-06T18:21:12Z | 17,593,272 | <p><code>feedparser</code> is now available for Python 2.4 up to 3.3- <a href="https://code.google.com/p/feedparser/" rel="nofollow">https://code.google.com/p/feedparser/</a></p>
| 2 | 2013-07-11T12:22:15Z | [
"python",
"rss",
"python-3.x",
"feeds"
] |
Pylucene in Python 2.6 + MacOs Snow Leopard | 1,527,332 | <p>Greetings,
I'm trying to install Pylucene on my 32-bit python running on Snow Leopard. I compiled JCC with success. But I get warnings while making pylucene:</p>
<pre><code>ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/__init__.o, file is not of required architecture
ld: warning: in build/temp.macos... | 0 | 2009-10-06T18:40:29Z | 1,527,722 | <p>Hard to say for sure, but could be as simple as jcc not being installed in the same python location. To troubleshoot I would try using jcc directly first. These commands should work even without lucene:</p>
<pre><code>>>> import jcc
>>> jcc.initVM(jcc.CLASSPATH)
<jcc.JCCEnv object at 0x100473... | 0 | 2009-10-06T19:52:34Z | [
"python",
"osx",
"lucene",
"pylucene",
"jcc"
] |
Pylucene in Python 2.6 + MacOs Snow Leopard | 1,527,332 | <p>Greetings,
I'm trying to install Pylucene on my 32-bit python running on Snow Leopard. I compiled JCC with success. But I get warnings while making pylucene:</p>
<pre><code>ld: warning: in build/temp.macosx-10.6-i386-2.6/build/_lucene/__init__.o, file is not of required architecture
ld: warning: in build/temp.macos... | 0 | 2009-10-06T18:40:29Z | 4,857,266 | <p>I had to adjust line 44 to 49 in the Makefile to get pylucene to install correctly:</p>
<pre><code>PREFIX_PYTHON=/my/virtualenv
ANT=ant
PYTHON=$(PREFIX_PYTHON)/bin/python
# add .__main__ to default configuration!
# --arch depends on your architecture of course
JCC=$(PYTHON) -m jcc.__main__ --shared --arch x86_64 ... | 1 | 2011-01-31T23:22:16Z | [
"python",
"osx",
"lucene",
"pylucene",
"jcc"
] |
How to do a Post Request in Python? | 1,527,337 | <p>Hi I'm sitting in a Greyhound Bus with Wifi and want to connect a second Device to the Network. But I have to accept an onscreen contract and the device does not have a browser.
To accept the contract the following form has to be accepted. The device has no CURL but all the standard python 2.6. libraries. </p>
<pr... | 6 | 2009-10-06T18:41:36Z | 1,527,561 | <p>I think this should do the trick:</p>
<pre><code>import urllib
data = urllib.urlencode({"mode_login":"Agree","redirect":"http://stackoverflow.com"})
result = urllib.urlopen("http://192.168.100.1:5280/",data).read()
print result
</code></pre>
| 2 | 2009-10-06T19:24:09Z | [
"python",
"networking",
"http-post"
] |
Constant instance variables? | 1,527,395 | <p>I use 'property' to ensure that changes to an objects instance variables are wrapped by methods where I need to. </p>
<p>What about when an instance has an variable that logically should not be changed? Eg, if I'm making a class for a Process, each Process instance should have a pid attribute that will frequently b... | 6 | 2009-10-06T18:56:00Z | 1,527,435 | <p>Maybe you can override <code>__setattr__</code>? In the line of,</p>
<pre><code>def __setattr__(self, name, value):
if self.__dict__.has_key(name):
raise TypeError, 'value is read only'
self.__dict__[name] = value
</code></pre>
| 1 | 2009-10-06T19:02:58Z | [
"python",
"properties",
"instance",
"setter",
"instance-variables"
] |
Constant instance variables? | 1,527,395 | <p>I use 'property' to ensure that changes to an objects instance variables are wrapped by methods where I need to. </p>
<p>What about when an instance has an variable that logically should not be changed? Eg, if I'm making a class for a Process, each Process instance should have a pid attribute that will frequently b... | 6 | 2009-10-06T18:56:00Z | 1,527,475 | <p>Prepend name of the variable with <code>__</code>, and create read-only property, Python will take care of exceptions, and variable itself will be protected from accidental overwrite.</p>
<pre><code>class foo(object):
def __init__(self, bar):
self.__bar = bar
@property
def bar(self):
re... | 6 | 2009-10-06T19:08:31Z | [
"python",
"properties",
"instance",
"setter",
"instance-variables"
] |
Constant instance variables? | 1,527,395 | <p>I use 'property' to ensure that changes to an objects instance variables are wrapped by methods where I need to. </p>
<p>What about when an instance has an variable that logically should not be changed? Eg, if I'm making a class for a Process, each Process instance should have a pid attribute that will frequently b... | 6 | 2009-10-06T18:56:00Z | 1,527,494 | <p>Simply trusting the user is not necessarily a bad thing; if you are just writing a quick Python program to be used once and thrown away, you might very well just trust that the user not alter the pid field.</p>
<p>IMHO the most Pythonic way to enforce the read-only field is to use a property that raises an exceptio... | 3 | 2009-10-06T19:11:39Z | [
"python",
"properties",
"instance",
"setter",
"instance-variables"
] |
Constant instance variables? | 1,527,395 | <p>I use 'property' to ensure that changes to an objects instance variables are wrapped by methods where I need to. </p>
<p>What about when an instance has an variable that logically should not be changed? Eg, if I'm making a class for a Process, each Process instance should have a pid attribute that will frequently b... | 6 | 2009-10-06T18:56:00Z | 1,528,413 | <p>Simply use a property and a hidden attribute (prefixed with <em>one</em> underscore).</p>
<p>Simple properties are read-only!</p>
<pre><code>>>> class Test (object):
... @property
... def bar(self):
... return self._bar
...
>>> t = Test()
>>> t._bar = 2
>>> t.bar
2
>>... | 1 | 2009-10-06T22:24:49Z | [
"python",
"properties",
"instance",
"setter",
"instance-variables"
] |
How do I convert Perl's pack 'Nc*' format to struct.pack for Python? | 1,527,534 | <p>I'm trying to convert a Perl script to python, and it uses quite a few different packs. I've been able to figure out the lettering differences in the "templates" for each one, but I'm having an issue with understanding how to handle Perl's lack of length declaration.</p>
<p>example:</p>
<pre><code>pack('Nc*',$some... | 5 | 2009-10-06T19:18:42Z | 1,527,651 | <p>Perl's pack is using the '*' character similar to in regular expressions--meaning a wildcard for more of the same. Here, of course, it means more signed ints.</p>
<p>In Python, you'd just loop through the string and concat the pieces:</p>
<pre><code>result = struct.pack('>L', some_integer)
for c in long_array_o... | 1 | 2009-10-06T19:38:13Z | [
"python",
"perl",
"struct",
"pack"
] |
How do I convert Perl's pack 'Nc*' format to struct.pack for Python? | 1,527,534 | <p>I'm trying to convert a Perl script to python, and it uses quite a few different packs. I've been able to figure out the lettering differences in the "templates" for each one, but I'm having an issue with understanding how to handle Perl's lack of length declaration.</p>
<p>example:</p>
<pre><code>pack('Nc*',$some... | 5 | 2009-10-06T19:18:42Z | 1,527,660 | <p>How about this?</p>
<pre><code>struct.pack('>I', some_integer) + struct.pack('b'*len(long_array), *long_array)
</code></pre>
| 7 | 2009-10-06T19:39:30Z | [
"python",
"perl",
"struct",
"pack"
] |
How does Google Books work? Are there any open source alternatives? | 1,527,549 | <p>I have been asked to publish a complete book online similar way Google Books does? i.e. it's viewable and printable but not download-able. </p>
<p>Is the process is basically "high quality scanning"? are there any open source solution to "mass generation" of "watermark" on those high quality images. Suppose you hav... | 0 | 2009-10-06T19:20:46Z | 1,527,572 | <p>Unfortunately Google uses a patented technique for scanning it's books, so you will probably have to stick to traditional methods.</p>
<blockquote>
<p>Google created some seriously nifty
infrared camera technology that
detects the three-dimensional shape
and angle of book pages when the book
is placed in ... | 4 | 2009-10-06T19:26:01Z | [
"python",
"image-processing",
"watermark"
] |
How does Google Books work? Are there any open source alternatives? | 1,527,549 | <p>I have been asked to publish a complete book online similar way Google Books does? i.e. it's viewable and printable but not download-able. </p>
<p>Is the process is basically "high quality scanning"? are there any open source solution to "mass generation" of "watermark" on those high quality images. Suppose you hav... | 0 | 2009-10-06T19:20:46Z | 1,527,576 | <p>Don't know much about Google Books, but <a href="http://www.pythonware.com/products/pil/" rel="nofollow">Python Imaging Library</a> can do watermarking (there's <a href="http://code.activestate.com/recipes/362879/" rel="nofollow">ASPN recipe</a> for that).</p>
| 1 | 2009-10-06T19:26:49Z | [
"python",
"image-processing",
"watermark"
] |
How does Google Books work? Are there any open source alternatives? | 1,527,549 | <p>I have been asked to publish a complete book online similar way Google Books does? i.e. it's viewable and printable but not download-able. </p>
<p>Is the process is basically "high quality scanning"? are there any open source solution to "mass generation" of "watermark" on those high quality images. Suppose you hav... | 0 | 2009-10-06T19:20:46Z | 1,527,600 | <p>See the <a href="http://ask.slashdot.org/story/09/09/27/199251/Software-To-Flatten-a-Photographed-Book?art%5Fpos=1" rel="nofollow">slashdot</a> question on reproducing Google's photo + laser grid technique.</p>
| 0 | 2009-10-06T19:29:51Z | [
"python",
"image-processing",
"watermark"
] |
How to use JQuery and Django (ajax + HttpResponse)? | 1,527,641 | <p>Suppose I have an AJAX function:</p>
<pre><code>function callpage{
$.ajax({
method:"get",
url:"/abc/",
data:"x="+3
beforeSend:function() {},
success:function(html){
IF HTTPRESPONSE = "1" , ALERT SUCCESS!
}
});
return false;
}
}
</code></pre>
<p>When my "View" executes in Djan... | 4 | 2009-10-06T19:37:05Z | 1,527,666 | <p>The typical workflow is to have the server return a JSON object as text, and then <a href="http://stackoverflow.com/questions/945015/alternatives-to-javascript-eval-for-parsing-json">interpret that object in the javascript</a>. In your case you could return the text {"httpresponse":1} from the server, or use the pyt... | 15 | 2009-10-06T19:41:04Z | [
"jquery",
"python",
"django"
] |
How to use JQuery and Django (ajax + HttpResponse)? | 1,527,641 | <p>Suppose I have an AJAX function:</p>
<pre><code>function callpage{
$.ajax({
method:"get",
url:"/abc/",
data:"x="+3
beforeSend:function() {},
success:function(html){
IF HTTPRESPONSE = "1" , ALERT SUCCESS!
}
});
return false;
}
}
</code></pre>
<p>When my "View" executes in Djan... | 4 | 2009-10-06T19:37:05Z | 1,604,495 | <p>Rather than do all this messy, low-level ajax and JSON stuff, consider using the <a href="http://malsup.com/jquery/taconite/" rel="nofollow">taconite plugin</a> for jQuery. You just make the call to the backend and it does the rest. It's well-documented and easy to debug -- especially if you are using Firebug with F... | 2 | 2009-10-22T01:04:03Z | [
"jquery",
"python",
"django"
] |
Python 2.6.2, Django 1.0.3, Windows XP, Page not found: / | 1,527,678 | <p>I'm just starting to learn Python and Django and an unable to get the most basic app working. I've setup Python, added python to the Path environment variable, installed Django using install.py script.</p>
<p>I created an app by running the command </p>
<pre><code>django-admin.py startproject my_project
</code></p... | 3 | 2009-10-06T19:43:58Z | 1,527,757 | <p>It sounds like you need to create some apps for your project and set up the urls. As you are just starting you'd be best following the tutorial right through to get a feel for it all.</p>
| 0 | 2009-10-06T19:58:33Z | [
"python",
"windows",
"django"
] |
Python 2.6.2, Django 1.0.3, Windows XP, Page not found: / | 1,527,678 | <p>I'm just starting to learn Python and Django and an unable to get the most basic app working. I've setup Python, added python to the Path environment variable, installed Django using install.py script.</p>
<p>I created an app by running the command </p>
<pre><code>django-admin.py startproject my_project
</code></p... | 3 | 2009-10-06T19:43:58Z | 3,937,055 | <p>To complete this question - @artran's answer of changing the port </p>
<pre><code>python manage.py runserver 8001
</code></pre>
<p>will work. </p>
<p>When python runs the server, it automatically uses port 8000 (hence <a href="http://127.0.0.1:8000/" rel="nofollow">http://127.0.0.1:8000/</a>). It uses this port a... | 2 | 2010-10-14T20:02:36Z | [
"python",
"windows",
"django"
] |
Python 2.6.2, Django 1.0.3, Windows XP, Page not found: / | 1,527,678 | <p>I'm just starting to learn Python and Django and an unable to get the most basic app working. I've setup Python, added python to the Path environment variable, installed Django using install.py script.</p>
<p>I created an app by running the command </p>
<pre><code>django-admin.py startproject my_project
</code></p... | 3 | 2009-10-06T19:43:58Z | 5,188,887 | <p>You probably have <code>ADMIN_MEDIA_PREFIX = ""</code> in your settings. Django intercepts requests to this url and attempts to serve admin media, thus when you make it an empty string, it will attempt to intercept ALL requests, resulting in nothing working.</p>
| 0 | 2011-03-04T02:04:15Z | [
"python",
"windows",
"django"
] |
exit from ipython | 1,527,689 | <p>I like IPython a lot for working with the python interpreter. However, I continually find myself typing <code>exit</code> to exit, and get prompted "Type exit() to exit." </p>
<p>I know I can type Ctrl-D to exit, but is there a way I can type <code>exit</code> without parentheses and get IPython to exit? </p>
<p><... | 10 | 2009-10-06T19:45:21Z | 1,527,713 | <p><code>%exit</code>, or <code>%Exit</code>, if you have confirmation enabled and want to skip it.
You can alias it to e.g. <code>%e</code> by putting <code>execute __IPYTHON__.magic_e = __IPYTHON__.magic_exit</code> in your ipythonrc.</p>
| 3 | 2009-10-06T19:49:54Z | [
"python",
"interpreter",
"ipython"
] |
exit from ipython | 1,527,689 | <p>I like IPython a lot for working with the python interpreter. However, I continually find myself typing <code>exit</code> to exit, and get prompted "Type exit() to exit." </p>
<p>I know I can type Ctrl-D to exit, but is there a way I can type <code>exit</code> without parentheses and get IPython to exit? </p>
<p><... | 10 | 2009-10-06T19:45:21Z | 1,528,023 | <pre><code>>>> import sys
>>> class Quitter(object):
... def __repr__(self):
... sys.exit()
...
>>> exit = Quitter()
</code></pre>
<p>You can use it like this:</p>
<pre><code>>>> exit
</code></pre>
<p><strong>EDIT:</strong></p>
<p>I dont use <code>ipython</code> myse... | 10 | 2009-10-06T20:48:33Z | [
"python",
"interpreter",
"ipython"
] |
exit from ipython | 1,527,689 | <p>I like IPython a lot for working with the python interpreter. However, I continually find myself typing <code>exit</code> to exit, and get prompted "Type exit() to exit." </p>
<p>I know I can type Ctrl-D to exit, but is there a way I can type <code>exit</code> without parentheses and get IPython to exit? </p>
<p><... | 10 | 2009-10-06T19:45:21Z | 4,515,356 | <p>At least in IPython 0.10, you should be able to set <strong>IPYTHON</strong>.rc.confirm_exit = False</p>
| 0 | 2010-12-23T02:17:58Z | [
"python",
"interpreter",
"ipython"
] |
Get records before and after current selection in Django query | 1,527,710 | <p>It sounds like an odd one but it's a really simple idea. I'm trying to make a simple Flickr for a website I'm building. This specific problem comes when I want to show a single photo (from my <code>Photo</code> model) on the page but I also want to show the image before it in the stream and the image after it.</p>
... | 1 | 2009-10-06T19:48:59Z | 1,528,013 | <p>I see the following possibilities:</p>
<ol>
<li><p>Your URL query parameters contain the sort/filtering information and some kind of 'item number', which is the item number <strong>within</strong> your filtered queryset. This is the simple case - previous and next are item number minus one and plus one respectivel... | 1 | 2009-10-06T20:44:43Z | [
"python",
"sql",
"django",
"django-models",
"django-queryset"
] |
Get records before and after current selection in Django query | 1,527,710 | <p>It sounds like an odd one but it's a really simple idea. I'm trying to make a simple Flickr for a website I'm building. This specific problem comes when I want to show a single photo (from my <code>Photo</code> model) on the page but I also want to show the image before it in the stream and the image after it.</p>
... | 1 | 2009-10-06T19:48:59Z | 1,528,122 | <p>You could try the following:</p>
<ol>
<li>Evaluate the filtered/sorted queryset and get the list of photo ids, which you hold in the session. These ids all match the filter/sort criteria.</li>
<li>Keep the current index into this list in the session too, and update it when the user moves to the previous/next photo.... | 1 | 2009-10-06T21:11:34Z | [
"python",
"sql",
"django",
"django-models",
"django-queryset"
] |
Regex for extraction in Python | 1,528,016 | <p>I have a string like this:</p>
<pre><code>"a word {{bla|123|456}} another {{bli|789|123}} some more text {{blu|789}} and more".
</code></pre>
<p>I would like to get this as an output:</p>
<pre><code>(("bla", 123, 456), ("bli", 789, 123), ("blu", 789))
</code></pre>
<p>I haven't been able to find the proper pytho... | 0 | 2009-10-06T20:45:35Z | 1,528,055 | <p>You need a lot of escapes in your regular expression since <code>{</code>, <code>}</code> and <code>|</code> are special characters in them. A first step to extract the relevant parts of the string would be this:</p>
<pre><code>regex = re.compile(r'\{\{(.*?)\|(.*?)(?:\|(.*?))?\}\}')
regex.findall(line)
</code></pre... | 1 | 2009-10-06T20:54:27Z | [
"python",
"regex"
] |
Regex for extraction in Python | 1,528,016 | <p>I have a string like this:</p>
<pre><code>"a word {{bla|123|456}} another {{bli|789|123}} some more text {{blu|789}} and more".
</code></pre>
<p>I would like to get this as an output:</p>
<pre><code>(("bla", 123, 456), ("bli", 789, 123), ("blu", 789))
</code></pre>
<p>I haven't been able to find the proper pytho... | 0 | 2009-10-06T20:45:35Z | 1,528,061 | <pre><code>>>> re.findall(' {{(\w+)\|(\w+)(?:\|(\w+))?}} ', s)
[('bla', '123', '456'), ('bli', '789', '123'), ('blu', '789', '')]
</code></pre>
<p>if you still want number there you'd need to iterate over the output and convert it to the integer with <code>int</code>.</p>
| 1 | 2009-10-06T20:56:55Z | [
"python",
"regex"
] |
Regex for extraction in Python | 1,528,016 | <p>I have a string like this:</p>
<pre><code>"a word {{bla|123|456}} another {{bli|789|123}} some more text {{blu|789}} and more".
</code></pre>
<p>I would like to get this as an output:</p>
<pre><code>(("bla", 123, 456), ("bli", 789, 123), ("blu", 789))
</code></pre>
<p>I haven't been able to find the proper pytho... | 0 | 2009-10-06T20:45:35Z | 1,528,087 | <pre><code>[re.split('\|', i) for i in re.findall("{{(.*?)}}", str)]
</code></pre>
<p>Returns:</p>
<pre><code>[['bla', '123', '456'], ['bli', '789', '123'], ['blu', '789']]
</code></pre>
<p>This method works regardless of the number of elements in the {{ }} blocks.</p>
| 0 | 2009-10-06T21:02:03Z | [
"python",
"regex"
] |
Regex for extraction in Python | 1,528,016 | <p>I have a string like this:</p>
<pre><code>"a word {{bla|123|456}} another {{bli|789|123}} some more text {{blu|789}} and more".
</code></pre>
<p>I would like to get this as an output:</p>
<pre><code>(("bla", 123, 456), ("bli", 789, 123), ("blu", 789))
</code></pre>
<p>I haven't been able to find the proper pytho... | 0 | 2009-10-06T20:45:35Z | 1,528,088 | <p>To get the exact output you wrote, you need a regex and a split:</p>
<pre><code>import re
map(lambda s: s.split("|"), re.findall(r"\{\{([^}]*)\}\}", s))
</code></pre>
<p>To get it with the numbers converted, do this:</p>
<pre><code>toint = lambda x: int(x) if x.isdigit() else x
[map(toint, p.split("|")) for p in ... | 0 | 2009-10-06T21:02:20Z | [
"python",
"regex"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.