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 list |
|---|---|---|---|---|---|---|---|---|---|
"Interfaces" in Python: Yea or Nay? | 552,058 | <p>So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to... | 16 | 2009-02-16T02:15:17Z | 552,087 | <p>There are some cases where interfaces can be very handy. <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> makes <a href="http://twistedmatrix.com/projects/core/documentation/howto/components.html" rel="nofollow">fairly extensive use</a> of <a href="http://wiki.zope.org/Interfaces/FrontPage" rel="... | 10 | 2009-02-16T02:40:12Z | [
"python",
"documentation",
"interface",
"coding-style"
] |
"Interfaces" in Python: Yea or Nay? | 552,058 | <p>So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to... | 16 | 2009-02-16T02:15:17Z | 552,093 | <p>I don't think interfaces would add anything to the code environment.</p>
<ul>
<li>Method definition enforcing happens without them. If an object expected to be have like <code>Foo</code> and have method <code>bar()</code>, and it does't, it will throw an <code>AttributeError</code>.</li>
<li>Simply making sure an i... | 6 | 2009-02-16T02:45:25Z | [
"python",
"documentation",
"interface",
"coding-style"
] |
"Interfaces" in Python: Yea or Nay? | 552,058 | <p>So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to... | 16 | 2009-02-16T02:15:17Z | 552,097 | <p>The pythonic way is to "Ask for forgiveness rather than receive permission". Interfaces are <em>all</em> about receiving permission to perform some operation on an object. Python prefers this:</p>
<pre><code>def quacker(duck):
try:
duck.quack():
except AttributeError:
raise ThisAintADuckEx... | 10 | 2009-02-16T02:46:40Z | [
"python",
"documentation",
"interface",
"coding-style"
] |
"Interfaces" in Python: Yea or Nay? | 552,058 | <p>So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to... | 16 | 2009-02-16T02:15:17Z | 552,112 | <p>You can create an interface in a dynamically typed language, but there's no enforcement of the interface at compile time. A statically typed language's compiler will warn you if you forget to implement (or mistype!) a method of an interface. Since you receive no such help in a dynamically typed language, your inte... | 4 | 2009-02-16T02:58:27Z | [
"python",
"documentation",
"interface",
"coding-style"
] |
"Interfaces" in Python: Yea or Nay? | 552,058 | <p>So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to... | 16 | 2009-02-16T02:15:17Z | 552,203 | <p>I'm not sure what the point of that is. Interfaces (of this form, anyway) are largely to work around the lack of multiple inheritance. But Python has MI, so why not just make an abstract class?</p>
<pre><code>class Something(object):
def some_method(self):
raise NotImplementedError()
def some_othe... | 27 | 2009-02-16T03:50:38Z | [
"python",
"documentation",
"interface",
"coding-style"
] |
"Interfaces" in Python: Yea or Nay? | 552,058 | <p>So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to... | 16 | 2009-02-16T02:15:17Z | 552,917 | <p>In Python 2.6 and later, you can use <a href="http://docs.python.org/library/abc.html">abstract base classes</a> instead. These are useful, because you can then test to see if something implements a given ABC by using "isinstance". As usual in Python, the concept is not as strictly enforced as it would be in a stric... | 11 | 2009-02-16T10:47:32Z | [
"python",
"documentation",
"interface",
"coding-style"
] |
"Interfaces" in Python: Yea or Nay? | 552,058 | <p>So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to... | 16 | 2009-02-16T02:15:17Z | 555,072 | <p>I personally use interfaces a lot in conjunction with the Zope Component Architecture (ZCA). The advantage is not so much to have interfaces but to be able to use them with adapters and utilities (singletons).</p>
<p>E.g. you could create an adapter which can take a class which implements ISomething but adapts it t... | 1 | 2009-02-16T23:48:49Z | [
"python",
"documentation",
"interface",
"coding-style"
] |
"Interfaces" in Python: Yea or Nay? | 552,058 | <p>So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to... | 16 | 2009-02-16T02:15:17Z | 555,960 | <p>Glyph Lefkowitz (of Twisted fame) just recently <a href="http://glyph.twistedmatrix.com/2009/02/explaining-why-interfaces-are-great.html" rel="nofollow">wrote an article on this topic</a>. Personally I do not feel the need for interfaces, but YMMV.</p>
| 1 | 2009-02-17T08:39:45Z | [
"python",
"documentation",
"interface",
"coding-style"
] |
"Interfaces" in Python: Yea or Nay? | 552,058 | <p>So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to... | 16 | 2009-02-16T02:15:17Z | 1,209,169 | <p>Have you looked at <a href="http://peak.telecommunity.com/PyProtocols.html" rel="nofollow">PyProtocols?</a> it has a nice interface implementation that you should look at.</p>
| 1 | 2009-07-30T20:32:01Z | [
"python",
"documentation",
"interface",
"coding-style"
] |
What's the best way to make a time from "Today" or "Yesterday" and a time in Python? | 552,073 | <p>Python has pretty good date parsing but is the only way to recognize a datetime such as "Today 3:20 PM" or "Yesterday 11:06 AM" by creating a new date today and doing subtractions?</p>
| 9 | 2009-02-16T02:30:50Z | 552,173 | <p>I am not yet completely up to speed on Python yet, but your question interested me, so I dug around a bit.</p>
<p>Date subtraction using <a href="http://docs.python.org/library/datetime.html#timedelta-objects" rel="nofollow"><strong><code>timedelta</code></strong></a> is by far the most common solution I found.</p>... | -2 | 2009-02-16T03:36:16Z | [
"python",
"datetime",
"parsing"
] |
What's the best way to make a time from "Today" or "Yesterday" and a time in Python? | 552,073 | <p>Python has pretty good date parsing but is the only way to recognize a datetime such as "Today 3:20 PM" or "Yesterday 11:06 AM" by creating a new date today and doing subtractions?</p>
| 9 | 2009-02-16T02:30:50Z | 552,229 | <p>A library that I like a lot, and I'm seeing more and more people use, is <a href="http://labix.org/python-dateutil">python-dateutil</a> but unfortunately neither it nor the other traditional big datetime parser, <a href="http://www.egenix.com/products/python/mxBase/mxDateTime/">mxDateTime from Egenix</a> can parse t... | 18 | 2009-02-16T04:03:58Z | [
"python",
"datetime",
"parsing"
] |
Missing first line when downloading .rar file using urllib2.urlopen() | 552,328 | <p>Okey this is really strange. I have this script which basically downloads bunch of achieve files and extracts them. Usually those files are .zip files. Today I sat down and decided to make it work with rar files and I got stuck. At first I thought that the problem is in my unrar code, but it wasn't there. So I did:<... | 0 | 2009-02-16T05:26:27Z | 552,346 | <p>Does the data maybe contain a "carriage return" character ("\r") so that the first chunk is overwritten with subsequent data when you try to display it? This would explain why you don't see the first chunk in your output, but not why you aren't able to decode it later on.</p>
| 2 | 2009-02-16T05:36:53Z | [
"python",
"urllib2"
] |
Missing first line when downloading .rar file using urllib2.urlopen() | 552,328 | <p>Okey this is really strange. I have this script which basically downloads bunch of achieve files and extracts them. Usually those files are .zip files. Today I sat down and decided to make it work with rar files and I got stuck. At first I thought that the problem is in my unrar code, but it wasn't there. So I did:<... | 0 | 2009-02-16T05:26:27Z | 552,390 | <p>When trying to determine the content of binary data string, use <a href="http://docs.python.org/library/functions.html#repr" rel="nofollow"><code>repr()</code></a> or <a href="http://docs.python.org/library/functions.html#hex" rel="nofollow"><code>hex()</code></a>. For example,</p>
<pre><code>>>> print rep... | 3 | 2009-02-16T06:10:34Z | [
"python",
"urllib2"
] |
How do python classes work? | 552,329 | <p>I have a code file from the boto framework pasted below, all of the print statements are mine, and the one commented out line is also mine, all else belongs to the attributed author.</p>
<p>My question is what is the order in which instantiations and allocations occur in python when instantiating a class? The auth... | 4 | 2009-02-16T05:26:35Z | 552,363 | <p><strong>A few python notes</strong></p>
<p>When python executes the <strong>class</strong> block, it creates all of the "attributes" of that class as it encounters them. They are usually class variables as well as functions (methods), and the like.</p>
<p>So the value for "Manager.DefaultDomainName" is set when i... | 9 | 2009-02-16T05:49:13Z | [
"python"
] |
How do python classes work? | 552,329 | <p>I have a code file from the boto framework pasted below, all of the print statements are mine, and the one commented out line is also mine, all else belongs to the attributed author.</p>
<p>My question is what is the order in which instantiations and allocations occur in python when instantiating a class? The auth... | 4 | 2009-02-16T05:26:35Z | 552,391 | <p>What gahooa said. Besides that, I assume that <code>boto.config.get(...)</code> returns <code>None</code>, presumably because the <code>default_domain</code> key is not defined in the <code>Persist</code> section of your config file.</p>
<p><code>boto.config</code> is defined in <code>boto/__init__.py</code> as <co... | 1 | 2009-02-16T06:12:28Z | [
"python"
] |
How do python classes work? | 552,329 | <p>I have a code file from the boto framework pasted below, all of the print statements are mine, and the one commented out line is also mine, all else belongs to the attributed author.</p>
<p>My question is what is the order in which instantiations and allocations occur in python when instantiating a class? The auth... | 4 | 2009-02-16T05:26:35Z | 552,432 | <p>when you load the module, python executes each of the code line by line. Since code is executed, class variables should all be set at load time. Most likely your boto.config.get function was just returned None. In another word, yes, all class variables are allocated before instance variables.</p>
| 0 | 2009-02-16T06:49:19Z | [
"python"
] |
How do python classes work? | 552,329 | <p>I have a code file from the boto framework pasted below, all of the print statements are mine, and the one commented out line is also mine, all else belongs to the attributed author.</p>
<p>My question is what is the order in which instantiations and allocations occur in python when instantiating a class? The auth... | 4 | 2009-02-16T05:26:35Z | 552,482 | <p>Thank you all for your help. I figured out what I was missing:</p>
<p>The class definitions of the boto classes I am using contain class variables for Manager, which in turn serve as a default value if no Manager is passed to the <code>__init__()</code> of these classes. I didn't even think about the fact that the... | 1 | 2009-02-16T07:23:28Z | [
"python"
] |
Use Python 2.6 subprocess module in Python 2.5 | 552,423 | <p>I would like to use Python 2.6's version of subprocess, because it allows the <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.terminate">Popen.terminate()</a> function, but I'm stuck with Python 2.5. Is there some reasonably clean way to use the newer version of the module in my 2.5 code? So... | 9 | 2009-02-16T06:41:55Z | 552,507 | <p>Well Python is open source, you are free to take that pthread function from 2.6 and move it into your own code or use it as a reference to implement your own.</p>
<p>For reasons that should be obvious there's no way to have a hybrid of Python that can import portions of newer versions.</p>
| 0 | 2009-02-16T07:38:05Z | [
"python",
"subprocess",
"python-2.5"
] |
Use Python 2.6 subprocess module in Python 2.5 | 552,423 | <p>I would like to use Python 2.6's version of subprocess, because it allows the <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.terminate">Popen.terminate()</a> function, but I'm stuck with Python 2.5. Is there some reasonably clean way to use the newer version of the module in my 2.5 code? So... | 9 | 2009-02-16T06:41:55Z | 552,510 | <p>There isn't really a great way to do it. subprocess is <a href="http://svn.python.org/view/python/trunk/Lib/subprocess.py?rev=69620&view=markup" rel="nofollow">implemented in python</a> (as opposed to C) so you could conceivably copy the module somewhere and use it (hoping of course that it doesn't use any 2.6 g... | 6 | 2009-02-16T07:39:07Z | [
"python",
"subprocess",
"python-2.5"
] |
Use Python 2.6 subprocess module in Python 2.5 | 552,423 | <p>I would like to use Python 2.6's version of subprocess, because it allows the <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.terminate">Popen.terminate()</a> function, but I'm stuck with Python 2.5. Is there some reasonably clean way to use the newer version of the module in my 2.5 code? So... | 9 | 2009-02-16T06:41:55Z | 552,543 | <p>While this doesn't directly answer your question, it may be worth knowing.</p>
<p>Imports from <code>__future__</code> actually only change compiler options, so while it can turn with into a statement or make string literals produce unicodes instead of strs, it can't change the capabilities and features of modules ... | 2 | 2009-02-16T07:57:50Z | [
"python",
"subprocess",
"python-2.5"
] |
Use Python 2.6 subprocess module in Python 2.5 | 552,423 | <p>I would like to use Python 2.6's version of subprocess, because it allows the <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.terminate">Popen.terminate()</a> function, but I'm stuck with Python 2.5. Is there some reasonably clean way to use the newer version of the module in my 2.5 code? So... | 9 | 2009-02-16T06:41:55Z | 554,881 | <p>I know this question has already been answered, but for what it's worth, I've used the <code>subprocess.py</code> that ships with Python 2.6 in Python 2.3 and it's worked fine. If you read the comments at the top of the file it says:</p>
<blockquote>
<p><code># This module should remain compatible with Python 2.2... | 9 | 2009-02-16T22:43:43Z | [
"python",
"subprocess",
"python-2.5"
] |
Use Python 2.6 subprocess module in Python 2.5 | 552,423 | <p>I would like to use Python 2.6's version of subprocess, because it allows the <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.terminate">Popen.terminate()</a> function, but I'm stuck with Python 2.5. Is there some reasonably clean way to use the newer version of the module in my 2.5 code? So... | 9 | 2009-02-16T06:41:55Z | 668,825 | <p>Here are some ways to end processes on Windows, taken directly from
<a href="http://code.activestate.com/recipes/347462/" rel="nofollow">http://code.activestate.com/recipes/347462/</a></p>
<pre><code># Create a process that won't end on its own
import subprocess
process = subprocess.Popen(['python.exe', '-c', 'whil... | 1 | 2009-03-21T05:57:12Z | [
"python",
"subprocess",
"python-2.5"
] |
Use Python 2.6 subprocess module in Python 2.5 | 552,423 | <p>I would like to use Python 2.6's version of subprocess, because it allows the <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.terminate">Popen.terminate()</a> function, but I'm stuck with Python 2.5. Is there some reasonably clean way to use the newer version of the module in my 2.5 code? So... | 9 | 2009-02-16T06:41:55Z | 1,449,566 | <p>I followed Kamil Kisiel suggestion regarding using python 2.6 subprocess.py in python 2.5 and it worked perfectly. To make it easier, I created a distutils package that you can easy_install and/or include in buildout.</p>
<p>To use subprocess from python 2.6 in python 2.5 project:</p>
<pre><code>easy_install taras... | 2 | 2009-09-19T21:21:16Z | [
"python",
"subprocess",
"python-2.5"
] |
Django Model returning NoneType | 552,521 | <p>I have a model Product</p>
<p>it has two fields size & colours among others</p>
<pre><code>colours = models.CharField(blank=True, null=True, max_length=500)
size = models.CharField(blank=True, null=True, max_length=500)
</code></pre>
<p>In my view I have </p>
<pre><code>current_product = Product.objects.get... | 2 | 2009-02-16T07:44:23Z | 552,530 | <p><code>NoneType</code> is the type that the <code>None</code> value has. You want to change the second snippet to</p>
<pre><code>if current_product.size: # This will evaluate as false if size is None or len(size) == 0.
blah blah
</code></pre>
| 7 | 2009-02-16T07:50:32Z | [
"python",
"django",
"django-views"
] |
Django Model returning NoneType | 552,521 | <p>I have a model Product</p>
<p>it has two fields size & colours among others</p>
<pre><code>colours = models.CharField(blank=True, null=True, max_length=500)
size = models.CharField(blank=True, null=True, max_length=500)
</code></pre>
<p>In my view I have </p>
<pre><code>current_product = Product.objects.get... | 2 | 2009-02-16T07:44:23Z | 552,532 | <p>NoneType is Pythons NULL-Type, meaning "nothing", "undefined". It has only one value: "None". When creating a new model object, its attributes are usually initialized to None, you can check that by comparing:</p>
<pre><code>if someobject.someattr is None:
# Not set yet
</code></pre>
| 1 | 2009-02-16T07:51:15Z | [
"python",
"django",
"django-views"
] |
Django Model returning NoneType | 552,521 | <p>I have a model Product</p>
<p>it has two fields size & colours among others</p>
<pre><code>colours = models.CharField(blank=True, null=True, max_length=500)
size = models.CharField(blank=True, null=True, max_length=500)
</code></pre>
<p>In my view I have </p>
<pre><code>current_product = Product.objects.get... | 2 | 2009-02-16T07:44:23Z | 552,538 | <p>I don't know Django, but I assume that some kind of ORM is involved when you do this:</p>
<pre><code>current_product = Product.objects.get(slug=title)
</code></pre>
<p>At that point you should always check whether you get None back ('None' is the same as 'null' in Java or 'nil' in Lisp with the subtle difference t... | -1 | 2009-02-16T07:54:08Z | [
"python",
"django",
"django-views"
] |
Django Model returning NoneType | 552,521 | <p>I have a model Product</p>
<p>it has two fields size & colours among others</p>
<pre><code>colours = models.CharField(blank=True, null=True, max_length=500)
size = models.CharField(blank=True, null=True, max_length=500)
</code></pre>
<p>In my view I have </p>
<pre><code>current_product = Product.objects.get... | 2 | 2009-02-16T07:44:23Z | 1,900,255 | <p>I can best explain the NoneType error with this example of erroneous code: </p>
<pre><code>def test():
s = list([1,'',2,3,4,'',5])
try:
s = s.remove('') # <-- THIS WRONG because it turns s in to a NoneType
except:
pass
print(str(s))
</code></pre>
<p><code>s.remove(... | 0 | 2009-12-14T11:05:55Z | [
"python",
"django",
"django-views"
] |
python ide vs cmd line detection? | 552,627 | <p>When programming in the two IDEs i used, bad things happen when i use raw_input. However on the command line it works EXACTLY how i expect it to. Typically this app is ran in cmd line but i like to edit and debug it in an IDE. Is there a way to detect if i executed the app in an IDE or not?</p>
| 0 | 2009-02-16T08:35:37Z | 552,634 | <pre><code>if sys.stdin.isatty():
# command line (not a pipe, no stdin redirection)
else:
# something else, could be IDE
</code></pre>
| 4 | 2009-02-16T08:39:45Z | [
"python"
] |
python ide vs cmd line detection? | 552,627 | <p>When programming in the two IDEs i used, bad things happen when i use raw_input. However on the command line it works EXACTLY how i expect it to. Typically this app is ran in cmd line but i like to edit and debug it in an IDE. Is there a way to detect if i executed the app in an IDE or not?</p>
| 0 | 2009-02-16T08:35:37Z | 553,304 | <p>I would strongly advise (and you have been previously advised on this) to use a good IDE, and a good debugger instead of hacking around your code to fix something that shouldn't be broken in the first place.</p>
<p>I deserve to be down-voted for not answering the question, but please consider this advice for your f... | 0 | 2009-02-16T13:30:24Z | [
"python"
] |
How do I profile memory usage in Python? | 552,744 | <p>I've recently become interested in algorithms and have begun exploring them by writing a naive implementation and then optimizing it in various ways.</p>
<p>I'm already familiar with the standard Python module for profiling runtime (for most things I've found the timeit magic function in IPython to be sufficient), ... | 87 | 2009-02-16T09:34:43Z | 552,810 | <p>This one has been answered already here: <a href="http://stackoverflow.com/questions/110259/python-memory-profiler">Python memory profiler</a></p>
<p>Basically you do something like that (cited from <a href="http://guppy-pe.sourceforge.net/#Heapy">Guppy-PE</a>):</p>
<pre><code>>>> from guppy import hpy; h... | 66 | 2009-02-16T10:00:24Z | [
"python",
"memory",
"profiling"
] |
How do I profile memory usage in Python? | 552,744 | <p>I've recently become interested in algorithms and have begun exploring them by writing a naive implementation and then optimizing it in various ways.</p>
<p>I'm already familiar with the standard Python module for profiling runtime (for most things I've found the timeit magic function in IPython to be sufficient), ... | 87 | 2009-02-16T09:34:43Z | 15,448,600 | <p>For a really simple approach try:</p>
<pre><code>import resource
def using(point=""):
usage=resource.getrusage(resource.RUSAGE_SELF)
return '''%s: usertime=%s systime=%s mem=%s mb
'''%(point,usage[0],usage[1],
(usage[2]*resource.getpagesize())/1000000.0 )
</code></pre>
<p>Just in... | 11 | 2013-03-16T11:19:27Z | [
"python",
"memory",
"profiling"
] |
How do I profile memory usage in Python? | 552,744 | <p>I've recently become interested in algorithms and have begun exploring them by writing a naive implementation and then optimizing it in various ways.</p>
<p>I'm already familiar with the standard Python module for profiling runtime (for most things I've found the timeit magic function in IPython to be sufficient), ... | 87 | 2009-02-16T09:34:43Z | 33,631,986 | <p>I you only want to look at the memory usage of an object, (<a href="http://stackoverflow.com/a/33631772/1587329">answer to other question</a>)</p>
<blockquote>
<p>There is a module called <a href="https://pypi.python.org/pypi/Pympler" rel="nofollow">Pympler</a> which contains the <code>asizeof</code>
module.</p... | 4 | 2015-11-10T14:13:21Z | [
"python",
"memory",
"profiling"
] |
python exit a blocking thread? | 552,996 | <p>in my code i loop though raw_input() to see if the user has requested to quit. My app can quit before the user quits, but my problem is the app is still alive until i enter a key to return from the blocking function raw_input(). Can i do to force raw_input() to return? by maybe sending it fake input? could i termina... | 2 | 2009-02-16T11:22:48Z | 553,290 | <p>You might use a non-blocking function to read user input.<br />
This solution is windows-specific:</p>
<pre><code>import msvcrt
import time
while True:
# test if there are keypresses in the input buffer
while msvcrt.kbhit():
# read a character
print msvcrt.getch()
# no keypresses, slee... | 2 | 2009-02-16T13:24:52Z | [
"python",
"multithreading",
"raw-input"
] |
python exit a blocking thread? | 552,996 | <p>in my code i loop though raw_input() to see if the user has requested to quit. My app can quit before the user quits, but my problem is the app is still alive until i enter a key to return from the blocking function raw_input(). Can i do to force raw_input() to return? by maybe sending it fake input? could i termina... | 2 | 2009-02-16T11:22:48Z | 553,333 | <p>You can use this time out function that wraps your function. Here's the recipe from: <a href="http://code.activestate.com/recipes/473878/" rel="nofollow">http://code.activestate.com/recipes/473878/</a></p>
<pre><code>def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
'''This function will ... | 3 | 2009-02-16T13:40:38Z | [
"python",
"multithreading",
"raw-input"
] |
python exit a blocking thread? | 552,996 | <p>in my code i loop though raw_input() to see if the user has requested to quit. My app can quit before the user quits, but my problem is the app is still alive until i enter a key to return from the blocking function raw_input(). Can i do to force raw_input() to return? by maybe sending it fake input? could i termina... | 2 | 2009-02-16T11:22:48Z | 553,438 | <p>There is a <a href="http://bytes.com/topic/python/answers/36171-need-function-like-raw_input-but-time-limit" rel="nofollow">post on the Python mailing list</a> which explains how to do this for Unix:</p>
<pre><code># this works on some platforms:
import signal, sys
def alarm_handler(*args):
raise Exception("t... | 1 | 2009-02-16T14:18:26Z | [
"python",
"multithreading",
"raw-input"
] |
python exit a blocking thread? | 552,996 | <p>in my code i loop though raw_input() to see if the user has requested to quit. My app can quit before the user quits, but my problem is the app is still alive until i enter a key to return from the blocking function raw_input(). Can i do to force raw_input() to return? by maybe sending it fake input? could i termina... | 2 | 2009-02-16T11:22:48Z | 553,509 | <p>Why don't you just mark the thread as daemonic?</p>
<p>From the <a href="http://docs.python.org/library/threading.html#id1" rel="nofollow">docs</a>:</p>
<blockquote>
<p>A thread can be flagged as a âdaemon threadâ. The significance of this flag is that the entire Python program exits when only daemon threads... | 6 | 2009-02-16T14:47:54Z | [
"python",
"multithreading",
"raw-input"
] |
python excel making reports | 553,019 | <p>I've been given the task of connecting my code (fortran) with py (2.5), and generate a number of excel reports if possible. The first part went fine - and is done with, but now I'm working on the second. </p>
<p>What are my choices for making excel (2007 if possible) sheets from python ? In general, I would need ... | 5 | 2009-02-16T11:30:16Z | 553,059 | <p>I believe you have two options:</p>
<ol>
<li>Control Excel from Python (using pywin32, see <a href="http://stackoverflow.com/questions/441758/driving-excel-from-python-in-windows/445961">this question</a>). Requires Windows and Excel.</li>
<li>Use the <a href="http://pypi.python.org/pypi/xlwt" rel="nofollow">xlwt</... | 2 | 2009-02-16T11:45:42Z | [
"python",
"excel"
] |
python excel making reports | 553,019 | <p>I've been given the task of connecting my code (fortran) with py (2.5), and generate a number of excel reports if possible. The first part went fine - and is done with, but now I'm working on the second. </p>
<p>What are my choices for making excel (2007 if possible) sheets from python ? In general, I would need ... | 5 | 2009-02-16T11:30:16Z | 553,069 | <p>You're simplest approach is to use Python's <a href="http://www.python.org/doc/2.5.2/lib/module-csv.html" rel="nofollow">csv</a> library to create a simple CSV file. Excel imports these effortlessly.</p>
<p>Then you do Excel stuff to make charts out of the pages created from CSV sheets.</p>
<p>There are some reci... | 3 | 2009-02-16T11:49:52Z | [
"python",
"excel"
] |
python excel making reports | 553,019 | <p>I've been given the task of connecting my code (fortran) with py (2.5), and generate a number of excel reports if possible. The first part went fine - and is done with, but now I'm working on the second. </p>
<p>What are my choices for making excel (2007 if possible) sheets from python ? In general, I would need ... | 5 | 2009-02-16T11:30:16Z | 553,091 | <p><a href="http://sourceforge.net/projects/pyexcelerator" rel="nofollow">PyExcelerator</a> has some quirks that you need to work around (atleast it did when I last used it), but it will do the job quite well.</p>
<p>I haven't tried <a href="http://pypi.python.org/pypi/xlwt" rel="nofollow">xlwt</a>, but as it's a fork... | 1 | 2009-02-16T11:59:45Z | [
"python",
"excel"
] |
python excel making reports | 553,019 | <p>I've been given the task of connecting my code (fortran) with py (2.5), and generate a number of excel reports if possible. The first part went fine - and is done with, but now I'm working on the second. </p>
<p>What are my choices for making excel (2007 if possible) sheets from python ? In general, I would need ... | 5 | 2009-02-16T11:30:16Z | 554,480 | <p>@S.Lott covered most of the bases. You might also consider generating an HTML <code><table></code>. Here's a sample I found with a quick search: <a href="http://www.developer.com/lang/other/print.php/10942_3727616_2" rel="nofollow">Creating Excel Files with Python and Django</a></p>
| 1 | 2009-02-16T20:41:25Z | [
"python",
"excel"
] |
python excel making reports | 553,019 | <p>I've been given the task of connecting my code (fortran) with py (2.5), and generate a number of excel reports if possible. The first part went fine - and is done with, but now I'm working on the second. </p>
<p>What are my choices for making excel (2007 if possible) sheets from python ? In general, I would need ... | 5 | 2009-02-16T11:30:16Z | 555,079 | <p>There is a package on PyPi call <a href="http://pypi.python.org/pypi/xlutils/" rel="nofollow">xlutils</a> which might help and there is <a href="http://www.simplistix.co.uk/presentations/python_excel_08/python_excel_08.pdf" rel="nofollow">this presentation from Chris Withers</a> (lightning talk from last EuroPython ... | 1 | 2009-02-16T23:53:40Z | [
"python",
"excel"
] |
python excel making reports | 553,019 | <p>I've been given the task of connecting my code (fortran) with py (2.5), and generate a number of excel reports if possible. The first part went fine - and is done with, but now I'm working on the second. </p>
<p>What are my choices for making excel (2007 if possible) sheets from python ? In general, I would need ... | 5 | 2009-02-16T11:30:16Z | 30,660,573 | <p>XslxWriter is a very good and very feature-complete python package for producing Excel worksheets.</p>
<p><a href="https://github.com/jmcnamara/XlsxWriter" rel="nofollow">https://github.com/jmcnamara/XlsxWriter</a> (docs: <a href="https://xlsxwriter.readthedocs.org/index.html" rel="nofollow">https://xlsxwriter.read... | 1 | 2015-06-05T07:16:48Z | [
"python",
"excel"
] |
Generate a random date between two other dates | 553,303 | <p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has ra... | 53 | 2009-02-16T13:30:04Z | 553,320 | <p>Convert both strings to timestamps (in your chosen resolution, e.g. milliseconds, seconds, hours, days, whatever), subtract the earlier from the later, multiply your random number (assuming it is distributed in the range [0, 1]) with that difference, and add again to the earlier one. Convert the timestamp back to d... | 70 | 2009-02-16T13:35:08Z | [
"python",
"datetime",
"random"
] |
Generate a random date between two other dates | 553,303 | <p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has ra... | 53 | 2009-02-16T13:30:04Z | 553,321 | <ol>
<li>Convert your input dates to numbers
(int, float, whatever is best for
your usage)</li>
<li>Choose a number between your two date numbers.</li>
<li>Convert this number back to a date.</li>
</ol>
<p>Many algorithms for converting date to and from numbers are already available in many operating systems.</p>
| 1 | 2009-02-16T13:35:26Z | [
"python",
"datetime",
"random"
] |
Generate a random date between two other dates | 553,303 | <p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has ra... | 53 | 2009-02-16T13:30:04Z | 553,323 | <p>What do you need the random number for? Usually (depending on the language) you can get the number of seconds/milliseconds from the Epoch from a date. So for a randomd date between startDate and endDate you could do:</p>
<ol>
<li>compute the time in ms between
startDate and endDate
(endDate.toMilliseconds() -
start... | 0 | 2009-02-16T13:36:11Z | [
"python",
"datetime",
"random"
] |
Generate a random date between two other dates | 553,303 | <p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has ra... | 53 | 2009-02-16T13:30:04Z | 553,325 | <p>Conceptually it's quite simple. Depending on which language you're using you will be able to convert those dates into some reference 32 or 64 bit integer, typically representing seconds since epoch (1 January 1970) otherwise known as "Unix time" or milliseconds since some other arbitrary date. Simply generate a ra... | 0 | 2009-02-16T13:37:45Z | [
"python",
"datetime",
"random"
] |
Generate a random date between two other dates | 553,303 | <p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has ra... | 53 | 2009-02-16T13:30:04Z | 553,337 | <p>The easiest way of doing this is to convert both numbers to timestamps, then set these as the minimum and maximum bounds on a random number generator.</p>
<p>A quick PHP example would be:</p>
<pre><code>// Find a randomDate between $start_date and $end_date
function randomDate($start_date, $end_date)
{
// Conv... | 3 | 2009-02-16T13:42:23Z | [
"python",
"datetime",
"random"
] |
Generate a random date between two other dates | 553,303 | <p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has ra... | 53 | 2009-02-16T13:30:04Z | 553,448 | <pre><code>from random import randrange
from datetime import timedelta
def random_date(start, end):
"""
This function will return a random datetime between two datetime
objects.
"""
delta = end - start
int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
random_second = randrange(int_de... | 67 | 2009-02-16T14:21:56Z | [
"python",
"datetime",
"random"
] |
Generate a random date between two other dates | 553,303 | <p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has ra... | 53 | 2009-02-16T13:30:04Z | 4,155,740 | <p>In python:</p>
<pre><code>>>> from dateutil.rrule import rrule, DAILY
>>> import datetime, random
>>> random.choice(
list(
rrule(DAILY,
dtstart=datetime.date(2009,8,21),
until=datetime.date(2010,... | 0 | 2010-11-11T15:00:59Z | [
"python",
"datetime",
"random"
] |
Generate a random date between two other dates | 553,303 | <p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has ra... | 53 | 2009-02-16T13:30:04Z | 6,127,309 | <p>Here is an answer to the literal meaning of the title rather than the body of this question:</p>
<pre><code>import time
import datetime
import random
def date_to_timestamp(d) :
return int(time.mktime(d.timetuple()))
def randomDate(start, end):
"""Get a random date between two dates"""
stime = date_to_times... | 2 | 2011-05-25T15:53:16Z | [
"python",
"datetime",
"random"
] |
Generate a random date between two other dates | 553,303 | <p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has ra... | 53 | 2009-02-16T13:30:04Z | 8,170,651 | <p>A tiny version.</p>
<pre><code>from datetime import timedelta
from random import randint
def random_date(start, end):
return start + timedelta(
seconds=randint(0, int((end - start).total_seconds())))
</code></pre>
<p>Note that both <code>start</code> and <code>end</code> arguments should be <code>dat... | 43 | 2011-11-17T16:25:52Z | [
"python",
"datetime",
"random"
] |
Generate a random date between two other dates | 553,303 | <p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has ra... | 53 | 2009-02-16T13:30:04Z | 17,127,561 | <p>Use ApacheCommonUtils to generate a random long within a given range,
and then create Date out of that long. </p>
<p>Example:</p>
<p>import org.apache.commons.math.random.RandomData;</p>
<p>import org.apache.commons.math.random.RandomDataImpl;</p>
<p>public Date nextDate(Date min, Date max) {</p>
<pre><code>Ran... | 0 | 2013-06-15T20:22:30Z | [
"python",
"datetime",
"random"
] |
Generate a random date between two other dates | 553,303 | <p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has ra... | 53 | 2009-02-16T13:30:04Z | 17,193,251 | <p>It's very simple using radar</p>
<h2>Installation</h2>
<p>$ pip install radar</p>
<h2>Usage</h2>
<pre class="lang-python prettyprint-override"><code>import datetime
import radar
# Generate random datetime (parsing dates from str values)
radar.random_datetime(start='2000-05-24', stop='2013-05-24T23:59:59')
# ... | 12 | 2013-06-19T13:59:56Z | [
"python",
"datetime",
"random"
] |
Generate a random date between two other dates | 553,303 | <p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has ra... | 53 | 2009-02-16T13:30:04Z | 22,222,900 | <p>To chip in a pandas-based solution I use:</p>
<pre><code>import pandas as pd
import numpy as np
def random_date(start, end, position=None):
start, end = pd.Timestamp(start), pd.Timestamp(end)
delta = (end - start).total_seconds()
if position is None:
offset = np.random.uniform(0., delta)
el... | 2 | 2014-03-06T11:18:51Z | [
"python",
"datetime",
"random"
] |
Generate a random date between two other dates | 553,303 | <p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has ra... | 53 | 2009-02-16T13:30:04Z | 26,819,041 | <p>Since Python 3 <code>timedelta</code> supports multiplication with floats, so now you can do:</p>
<pre><code>import random
random_date = start + (end - start) * random.random()
</code></pre>
<p>given that <code>start</code> and <code>end</code> are of the type <code>datetime.datetime</code>. For example, to genera... | 2 | 2014-11-08T15:56:45Z | [
"python",
"datetime",
"random"
] |
Generate a random date between two other dates | 553,303 | <p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has ra... | 53 | 2009-02-16T13:30:04Z | 26,883,710 | <p>You can Use <code>Mixer</code>,</p>
<pre><code>pip install mixer
</code></pre>
<p>and,</p>
<pre><code>from mixer import generators as gen
print gen.get_datetime(min_datetime=(1900, 1, 1, 0, 0, 0), max_datetime=(2020, 12, 31, 23, 59, 59))
</code></pre>
| 2 | 2014-11-12T09:42:53Z | [
"python",
"datetime",
"random"
] |
Generate a random date between two other dates | 553,303 | <p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has ra... | 53 | 2009-02-16T13:30:04Z | 35,709,408 | <p>This is a different approach - that sort of works..</p>
<pre><code>from random import randint
import datetime
date=datetime.date(randint(2005,2025), randint(1,12),randint(1,28))
</code></pre>
<p><strong>WAIITT - BETTER APPROACH</strong></p>
<pre><code>startdate=datetime.date(YYYY,MM,DD)
date=startdate+datetime.t... | 3 | 2016-02-29T20:52:42Z | [
"python",
"datetime",
"random"
] |
Generate a random date between two other dates | 553,303 | <p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has ra... | 53 | 2009-02-16T13:30:04Z | 36,231,794 | <p>I made this for another project using random and time. I used a general format from time you can view the documentation <a href="https://docs.python.org/2/library/time.html#time.struct_time" rel="nofollow">here</a> for the first argument in strftime(). The second part is a random.randrange function. It returns an in... | 0 | 2016-03-26T04:58:26Z | [
"python",
"datetime",
"random"
] |
Generate a random date between two other dates | 553,303 | <p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has ra... | 53 | 2009-02-16T13:30:04Z | 38,039,865 | <p>Just to add another one:</p>
<pre><code>datestring = datetime.datetime.strftime(datetime.datetime( \
random.randint(2000, 2015), \
random.randint(1, 12), \
random.randint(1, 28), \
random.randrange(23), \
random.randrange(59), \
random.randrange(59), \
random.randrange(1000000)), '%Y-%m-... | 0 | 2016-06-26T15:08:01Z | [
"python",
"datetime",
"random"
] |
Windows Server 2008 or Vista? | 553,372 | <p>What is an easy (to implement) way to check whether I am on Windows Vista or Windows Server 2008 from a Python script?</p>
<p><code>platform.uname()</code> gives the same result for both versions.</p>
| 1 | 2009-02-16T13:58:23Z | 553,427 | <p>As mentioned in the other question the foolproof (I think) way is to use win32api.GetVersionEx(1). The combination of the version number and the product type will give you the current windows platform you're running on. Eg. the combination of version number "6.*" and product type VER_NT_SERVER is Windows Server 2008... | 2 | 2009-02-16T14:13:51Z | [
"python",
"windows-vista",
"windows-server-2008",
"windowsversion"
] |
Can you use a string to instantiate a class in python? | 553,784 | <p>I'm using a builder pattern to seperate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named an ID (something like ID12345). These all inherit from the base builder class. In my script, I need to instantiate an instance for each class (about 50) every time this app ru... | 27 | 2009-02-16T16:00:26Z | 554,034 | <p>There's some stuff missing from your question, so I'm forced to guess at the omitted stuff. Feel free to edit your question to correct the omissions.</p>
<pre><code>class ProcessDirector( object ):
# does something
class ID12345( SomeKindOfProcess ):
pass
class ID001234( SomeKindOfProcess ):
pass
id... | -1 | 2009-02-16T18:08:37Z | [
"python",
"design-patterns",
"reflection"
] |
Can you use a string to instantiate a class in python? | 553,784 | <p>I'm using a builder pattern to seperate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named an ID (something like ID12345). These all inherit from the base builder class. In my script, I need to instantiate an instance for each class (about 50) every time this app ru... | 27 | 2009-02-16T16:00:26Z | 554,073 | <p><strong>Never</strong> use <code>eval()</code> if you can help it. Python has <strong>so</strong> many better options (dispatch dictionary, <code>getattr()</code>, etc.) that you should never have to use the security hole known as <code>eval()</code>.</p>
| 12 | 2009-02-16T18:17:22Z | [
"python",
"design-patterns",
"reflection"
] |
Can you use a string to instantiate a class in python? | 553,784 | <p>I'm using a builder pattern to seperate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named an ID (something like ID12345). These all inherit from the base builder class. In my script, I need to instantiate an instance for each class (about 50) every time this app ru... | 27 | 2009-02-16T16:00:26Z | 554,162 | <p>Simplest way is to just create a dict.</p>
<pre><code>class A(object):
pass
class B(object):
pass
namedclass = {'ID12345': A, 'ID2': A, 'B': B, 'AnotherB': B, 'ID01234': B}
</code></pre>
<p>Then use it (your code example):</p>
<pre><code>IDS = ["ID12345", "ID01234"]
ProcessDirector = ProcessDirector(... | 4 | 2009-02-16T18:46:28Z | [
"python",
"design-patterns",
"reflection"
] |
Can you use a string to instantiate a class in python? | 553,784 | <p>I'm using a builder pattern to seperate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named an ID (something like ID12345). These all inherit from the base builder class. In my script, I need to instantiate an instance for each class (about 50) every time this app ru... | 27 | 2009-02-16T16:00:26Z | 554,462 | <p>If you wanted to avoid an eval(), you could just do:</p>
<pre><code>id = "1234asdf"
constructor = globals()[id]
instance = constructor()
</code></pre>
<p>Provided that the class is defined in (or imported into) your current scope.</p>
| 39 | 2009-02-16T20:34:50Z | [
"python",
"design-patterns",
"reflection"
] |
Can you use a string to instantiate a class in python? | 553,784 | <p>I'm using a builder pattern to seperate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named an ID (something like ID12345). These all inherit from the base builder class. In my script, I need to instantiate an instance for each class (about 50) every time this app ru... | 27 | 2009-02-16T16:00:26Z | 554,812 | <p>Not totally sure this is what you want, but it seems like a more Python'y way to instantiate a bunch of classes listed in a string:</p>
<pre><code>class idClasses:
class ID12345:pass
class ID01234:pass
# could also be: import idClasses
class ProcessDirector:
def __init__(self):
self.allClasses ... | 13 | 2009-02-16T22:18:24Z | [
"python",
"design-patterns",
"reflection"
] |
Can anyone provide a more pythonic way of generating the morris sequence? | 553,871 | <p>I'm trying to generate the <a href="http://www.ocf.berkeley.edu/~stoll/answer.html" rel="nofollow">morris sequence</a> in python. My current solution is below, but I feel like I just wrote c in python. Can anyone provide a more pythonic solution?</p>
<pre><code>def morris(x):
a = ['1', '11']
yield a[0]
... | 5 | 2009-02-16T16:24:53Z | 554,002 | <pre><code>from itertools import groupby, islice
def morris():
morris = '1'
yield morris
while True:
morris = groupby(morris)
morris = ((len(list(group)), key) for key, group in morris)
morris = ((str(l), k) for l, k in morris)
morris = ''.join(''.join(t) for t in morris)
... | 6 | 2009-02-16T18:01:25Z | [
"python",
"sequences",
"itertools"
] |
Can anyone provide a more pythonic way of generating the morris sequence? | 553,871 | <p>I'm trying to generate the <a href="http://www.ocf.berkeley.edu/~stoll/answer.html" rel="nofollow">morris sequence</a> in python. My current solution is below, but I feel like I just wrote c in python. Can anyone provide a more pythonic solution?</p>
<pre><code>def morris(x):
a = ['1', '11']
yield a[0]
... | 5 | 2009-02-16T16:24:53Z | 554,028 | <p><a href="http://docs.python.org/library/itertools.html#itertools.groupby"><code>itertools.groupby</code></a> seems to fit perfectly! Just define a <code>next_morris</code> function as follows:</p>
<pre><code>def next_morris(number):
return ''.join('%s%s' % (len(list(group)), digit)
for digit,... | 23 | 2009-02-16T18:07:12Z | [
"python",
"sequences",
"itertools"
] |
How do I prevent Python's urllib(2) from following a redirect | 554,446 | <p>I am currently trying to log into a site using Python however the site seems to be sending a cookie and a redirect statement on the same page. Python seems to be following that redirect thus preventing me from reading the cookie send by the login page. How do I prevent Python's urllib (or urllib2) urlopen from fol... | 40 | 2009-02-16T20:29:30Z | 554,475 | <p><code>urllib2.urlopen</code> calls <code>build_opener()</code> which uses this list of handler classes:</p>
<pre><code>handlers = [ProxyHandler, UnknownHandler, HTTPHandler,
HTTPDefaultErrorHandler, HTTPRedirectHandler,
FTPHandler, FileHandler, HTTPErrorProcessor]
</code></pre>
<p>You could try calling <code>urlli... | 11 | 2009-02-16T20:38:43Z | [
"python",
"urllib2"
] |
How do I prevent Python's urllib(2) from following a redirect | 554,446 | <p>I am currently trying to log into a site using Python however the site seems to be sending a cookie and a redirect statement on the same page. Python seems to be following that redirect thus preventing me from reading the cookie send by the login page. How do I prevent Python's urllib (or urllib2) urlopen from fol... | 40 | 2009-02-16T20:29:30Z | 554,501 | <p>This question was asked before <a href="http://stackoverflow.com/questions/110498/is-there-an-easy-way-to-request-a-url-in-python-and-not-follow-redirects/110808">here</a>.</p>
<p><b>EDIT:</b> If you have to deal with quirky web applications you should probably try out <a href="http://wwwsearch.sourceforge.net/mech... | 3 | 2009-02-16T20:46:59Z | [
"python",
"urllib2"
] |
How do I prevent Python's urllib(2) from following a redirect | 554,446 | <p>I am currently trying to log into a site using Python however the site seems to be sending a cookie and a redirect statement on the same page. Python seems to be following that redirect thus preventing me from reading the cookie send by the login page. How do I prevent Python's urllib (or urllib2) urlopen from fol... | 40 | 2009-02-16T20:29:30Z | 554,580 | <p>You could do a couple of things:</p>
<ol>
<li>Build your own HTTPRedirectHandler that intercepts each redirect</li>
<li>Create an instance of HTTPCookieProcessor and install that opener so that you have access to the cookiejar.</li>
</ol>
<p>This is a quick little thing that shows both</p>
<pre><code>import urlli... | 33 | 2009-02-16T21:13:43Z | [
"python",
"urllib2"
] |
How do I prevent Python's urllib(2) from following a redirect | 554,446 | <p>I am currently trying to log into a site using Python however the site seems to be sending a cookie and a redirect statement on the same page. Python seems to be following that redirect thus preventing me from reading the cookie send by the login page. How do I prevent Python's urllib (or urllib2) urlopen from fol... | 40 | 2009-02-16T20:29:30Z | 11,744,894 | <p>If all you need is stopping redirection, then there is a simple way to do it. For example I only want to get cookies and for a better performance I don't want to be redirected to any other page. Also I hope the code is kept as 3xx. let's use 302 for instance.</p>
<pre><code>class MyHTTPErrorProcessor(urllib2.HTTPEr... | 27 | 2012-07-31T16:33:51Z | [
"python",
"urllib2"
] |
Stackless python network performance degrading over time? | 554,805 | <p>So i'm toying around with stackless python, writing a <em>very simple</em> webserver to teach myself programming with microthreads/tasklets. But now to my problem, when I run something like <code>ab -n 100000 -c 50 http://192.168.0.192/</code> (100k requests, 50 concurrency) in apache bench I get something like 6k r... | 8 | 2009-02-16T22:16:06Z | 554,914 | <p>Two things.</p>
<p>First, please make Class Name start with an Upper Case Letter. It's more conventional and easier to read.</p>
<p>More importantly, in the <code>stackless_accept</code> function you accumulate a <code>list</code> of <code>Sock</code> objects, named <code>sockets</code>. This list appears to gro... | 14 | 2009-02-16T22:52:41Z | [
"python",
"performance",
"networking",
"io",
"python-stackless"
] |
Parameterised regular expression in Python | 554,957 | <p>In Python, is there a better way to <strong>parameterise strings into regular expressions</strong> than doing it manually like this:</p>
<pre><code>test = 'flobalob'
names = ['a', 'b', 'c']
for name in names:
regexp = "%s" % (name)
print regexp, re.search(regexp, test)
</code></pre>
<p><em>This noddy examp... | 3 | 2009-02-16T23:07:59Z | 554,989 | <p>Well, as you build a regexp from a string, I see no other way. But you could <em>parameterise the string itself</em> with a dictionary:</p>
<pre><code>d = {'bar': 'a', 'foo': 'b'}
regexp = '%(foo)s|%(bar)s' % d
</code></pre>
<p>Or, depending on the problem, you could use list comprehensions:</p>
<pre><code>vlist... | 6 | 2009-02-16T23:15:59Z | [
"python",
"regex"
] |
Parameterised regular expression in Python | 554,957 | <p>In Python, is there a better way to <strong>parameterise strings into regular expressions</strong> than doing it manually like this:</p>
<pre><code>test = 'flobalob'
names = ['a', 'b', 'c']
for name in names:
regexp = "%s" % (name)
print regexp, re.search(regexp, test)
</code></pre>
<p><em>This noddy examp... | 3 | 2009-02-16T23:07:59Z | 555,052 | <pre><code>import fnmatch, os
filenames = ['bob.txt', 'fred.txt', 'paul.txt']
# 'b.txt.b' -> 'b.txt*.b'
filepatterns = ((f, '*'.join(os.path.splitext(f))) for f in filenames)
diskfilenames = filter(os.path.isfile, os.listdir(''))
pattern2filenames = dict((fn, fnmatch.filter(diskfilenames, pat))
... | 2 | 2009-02-16T23:40:00Z | [
"python",
"regex"
] |
Parameterised regular expression in Python | 554,957 | <p>In Python, is there a better way to <strong>parameterise strings into regular expressions</strong> than doing it manually like this:</p>
<pre><code>test = 'flobalob'
names = ['a', 'b', 'c']
for name in names:
regexp = "%s" % (name)
print regexp, re.search(regexp, test)
</code></pre>
<p><em>This noddy examp... | 3 | 2009-02-16T23:07:59Z | 555,055 | <p>may be <a href="http://docs.python.org/library/glob.html" rel="nofollow">glob</a> and <a href="http://docs.python.org/library/fnmatch.html" rel="nofollow">fnmatch</a> modules can be of some help for you?</p>
| 2 | 2009-02-16T23:41:48Z | [
"python",
"regex"
] |
Euler problem number #4 | 555,009 | <p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the large... | 2 | 2009-02-16T23:21:46Z | 555,020 | <p>Try computing x from the product of z and y rather than checking every number from 1 to a million. Think about it: if you were asked to calculate 500*240, which is more efficient - multiplying them, or counting up from 1 until you find the right answer?</p>
| 9 | 2009-02-16T23:25:00Z | [
"python",
"palindrome"
] |
Euler problem number #4 | 555,009 | <p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the large... | 2 | 2009-02-16T23:21:46Z | 555,023 | <p>comparing string with an integer in</p>
<pre><code>x == z*y
</code></pre>
<p>there are also logical errors</p>
<p>start in reverse order <code>range(999, 99, -1)</code>. that'll be more efficient. remove third loop and second comparison altogether.</p>
| 1 | 2009-02-16T23:25:30Z | [
"python",
"palindrome"
] |
Euler problem number #4 | 555,009 | <p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the large... | 2 | 2009-02-16T23:21:46Z | 555,098 | <p>The question states:</p>
<pre><code>What is the largest prime factor of the number 600851475143?
</code></pre>
<p>I solved this using C#, but the algorithm itself is language-agnostic.</p>
<ol>
<li>Create a method for determining if a number is prime or not. This can be brute-force (rather than using a much more... | 0 | 2009-02-17T00:04:09Z | [
"python",
"palindrome"
] |
Euler problem number #4 | 555,009 | <p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the large... | 2 | 2009-02-16T23:21:46Z | 555,107 | <p>Some efficiency issues:</p>
<ol>
<li>start at the top (since we can use this in skipping a lot of calculations)</li>
<li>don't double-calculate</li>
</ol>
<blockquote>
<pre><code>def is_palindrome(n):
s = str(n)
return s == s[::-1]
def biggest():
big_x, big_y, max_seen = 0,0, 0
for x in xrange(999... | 9 | 2009-02-17T00:08:11Z | [
"python",
"palindrome"
] |
Euler problem number #4 | 555,009 | <p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the large... | 2 | 2009-02-16T23:21:46Z | 555,135 | <p>rather than enumerating all products of 3-digit numbers (~900^2 iterations),
enumerate all 6- and 5-digit palyndromes (this takes ~1000 iterations);
then for each palyndrome decide whether it can be represented by a product
of two 3-digit numbers (if it can't, it should have a 4-digit prime factor,
so this is kind o... | 1 | 2009-02-17T00:20:51Z | [
"python",
"palindrome"
] |
Euler problem number #4 | 555,009 | <p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the large... | 2 | 2009-02-16T23:21:46Z | 555,167 | <p>If your program is running slow, and you have nested loops like this:</p>
<pre><code>for z in range(100, 1000):
for y in range(100, 1000):
for x in range(1, 1000000):
</code></pre>
<p>Then a question you should ask yourself is: "How many times will the body of the innermost loop execute?" (the body of... | -1 | 2009-02-17T00:36:52Z | [
"python",
"palindrome"
] |
Euler problem number #4 | 555,009 | <p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the large... | 2 | 2009-02-16T23:21:46Z | 555,217 | <p>This is what I did in Java:</p>
<pre><code>public class Euler0004
{
//assumes positive int
static boolean palindrome(int p)
{
//if there's only one char, then it's
// automagically a palindrome
if(p < 10)
return true;
char[] c = String.valueOf(p).toCharArray();
//loo... | -1 | 2009-02-17T01:10:10Z | [
"python",
"palindrome"
] |
Euler problem number #4 | 555,009 | <p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the large... | 2 | 2009-02-16T23:21:46Z | 555,218 | <p>Here's some general optimizations to keep in mind. The posted code handles all of this, but these are general rules to learn that might help with future problems:</p>
<p>1) if you've already checked z = 995, y = 990, you don't need to check z = 990, y = 995. Greg Lind handles this properly</p>
<p>2) You calculate ... | 3 | 2009-02-17T01:10:59Z | [
"python",
"palindrome"
] |
Euler problem number #4 | 555,009 | <p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the large... | 2 | 2009-02-16T23:21:46Z | 2,129,160 | <p>The other advice here is great. This code also works. I start with 999 because we know the largest combination possible is 999*999. Not python, but some quickly done pseudo code. </p>
<pre><code>public static int problem4()
{
int biggestSoFar=0;
for(int i = 999; i>99;i--){
for(... | 0 | 2010-01-24T22:27:31Z | [
"python",
"palindrome"
] |
Euler problem number #4 | 555,009 | <p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the large... | 2 | 2009-02-16T23:21:46Z | 6,397,877 | <p>Here is my solution:</p>
<pre><code>polindroms = [(x, y, x * y) for x in range(100, 999) for y in range(100, 999) if str(x * y) == str(x * y)[::-1]]
print max(polindroms, key = lambda item : item[2])
</code></pre>
| -1 | 2011-06-18T18:03:15Z | [
"python",
"palindrome"
] |
Euler problem number #4 | 555,009 | <p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the large... | 2 | 2009-02-16T23:21:46Z | 14,146,888 | <p>This adds a couple of optimizations to @GreggLind's good solution, cutting the run time in half:</p>
<pre><code>def is_palindrome(n):
s = str(n)
return s == s[::-1]
def biggest():
big_x, big_y, max_seen = 0,0, 0
for x in xrange(999,99,-1):
# Optim. 1: Nothing in any row from here on can be ... | 0 | 2013-01-03T20:39:36Z | [
"python",
"palindrome"
] |
Euler problem number #4 | 555,009 | <p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the large... | 2 | 2009-02-16T23:21:46Z | 14,148,086 | <p>Wow, this approach improves quite a bit over other implementations on this page, including <a href="http://stackoverflow.com/a/14146888/423105">mine</a>.</p>
<p>Instead of</p>
<ul>
<li>walking down the three-digit factors row by row (first do all y for x = 999, then all y for x = 998, etc.),</li>
</ul>
<p>we</p>
... | 1 | 2013-01-03T22:11:23Z | [
"python",
"palindrome"
] |
Euler problem number #4 | 555,009 | <p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the large... | 2 | 2009-02-16T23:21:46Z | 14,149,395 | <p>Here is a solution that you might consider. It could be far more efficient but only takes a little time to run.</p>
<pre><code>largest = 0
for a in range(100, 1000):
for b in range(100, 1000):
c = a * b
if str(c) == ''.join(reversed(str(c))):
largest = max(largest, c)
print(largest)
... | 0 | 2013-01-04T00:19:00Z | [
"python",
"palindrome"
] |
Euler problem number #4 | 555,009 | <p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the large... | 2 | 2009-02-16T23:21:46Z | 16,471,389 | <p>Here is an efficient general solution (~5x faster than others I have seen):</p>
<pre><code>def pgen(factor):
''' Generates stream of palindromes smaller than factor**2
starting with largest possible palindrome '''
pmax = str(factor**2)
half_palindrome = int(pmax[0:len(pmax)/2]) - 1
for x in... | 0 | 2013-05-09T21:24:48Z | [
"python",
"palindrome"
] |
Multiple output files | 555,146 | <p>edit: Initially I was trying to be general but it came out vague. I've included more detail below. </p>
<p>I'm writing a script that pulls in data from two large CSV files, one of people's schedules and the other of information about their schedules. The data is mined and combined to eventually create pajek format ... | 0 | 2009-02-17T00:29:18Z | 555,159 | <p>I would open seven file streams as accumulating them might be quite memory extensive if it's a lot of data. Of course that is only an option if you can sort them live and don't first need all data read to do the sorting.</p>
| 2 | 2009-02-17T00:34:36Z | [
"python",
"file-io"
] |
Multiple output files | 555,146 | <p>edit: Initially I was trying to be general but it came out vague. I've included more detail below. </p>
<p>I'm writing a script that pulls in data from two large CSV files, one of people's schedules and the other of information about their schedules. The data is mined and combined to eventually create pajek format ... | 0 | 2009-02-17T00:29:18Z | 555,396 | <p><strong>"...pulls in data from two large CSV files, one of people's schedules and the other of information about their schedules."</strong> Vague, but I think I get it.</p>
<p><strong>"The data is mined and combined to eventually create pajek format graphs for Monday-Sat of peoples connections,"</strong> Mined an... | 2 | 2009-02-17T02:56:04Z | [
"python",
"file-io"
] |
Match series of (non-nested) balanced parentheses at end of string | 555,344 | <p>How can I match one or more parenthetical expressions appearing at the end of string?</p>
<p>Input:</p>
<pre><code>'hello (i) (m:foo)'
</code></pre>
<p>Desired output:</p>
<pre><code>['i', 'm:foo']
</code></pre>
<p>Intended for a python script. Paren marks cannot appear inside of each other (<a href="http://i89... | 3 | 2009-02-17T02:29:03Z | 555,370 | <p>You don't <em>need</em> to use regex:</p>
<pre><code>def splitter(input):
return [ s.rstrip(" \t)") for s in input.split("(") ][1:]
print splitter('hello (i) (m:foo)')
</code></pre>
<p><strong>Note:</strong> this solution only works if your input is already known to be valid. See MizardX's solution that will w... | 5 | 2009-02-17T02:40:33Z | [
"python",
"regex"
] |
Match series of (non-nested) balanced parentheses at end of string | 555,344 | <p>How can I match one or more parenthetical expressions appearing at the end of string?</p>
<p>Input:</p>
<pre><code>'hello (i) (m:foo)'
</code></pre>
<p>Desired output:</p>
<pre><code>['i', 'm:foo']
</code></pre>
<p>Intended for a python script. Paren marks cannot appear inside of each other (<a href="http://i89... | 3 | 2009-02-17T02:29:03Z | 555,404 | <pre><code>paren_pattern = re.compile(r"\(([^()]*)\)(?=(?:\s*\([^()]*\))*\s*$)")
def getParens(s):
return paren_pattern.findall(s)
</code></pre>
<p>or even shorter:</p>
<pre><code>getParens = re.compile(r"\(([^()]*)\)(?=(?:\s*\([^()]*\))*\s*$)").findall
</code></pre>
<p>explaination:</p>
<pre><code>\( ... | 7 | 2009-02-17T03:02:58Z | [
"python",
"regex"
] |
Getting a list of all modules in the current package | 555,571 | <p>Here's what I want to do: I want to build a test suite that's organized into packages like tests.ui, tests.text, tests.fileio, etc. In each <code>__</code>init<code>__</code>.py in these packages, I want to make a test suite consisting of all the tests in all the modules in that package. Of course, getting all th... | 0 | 2009-02-17T05:02:44Z | 555,682 | <p>You can use os.listdir to find all files in the test.* directory and then filter out .py files:</p>
<pre><code># Place this code to your __init__.py in test.* directory
import os
modules = []
for name in os.listdir(os.path.dirname(os.path.abspath(__file__))):
m, ext = os.path.splitext()
if ext == '.py':
... | 1 | 2009-02-17T06:20:25Z | [
"python",
"unit-testing",
"module",
"packages",
"python-2.5"
] |
Getting a list of all modules in the current package | 555,571 | <p>Here's what I want to do: I want to build a test suite that's organized into packages like tests.ui, tests.text, tests.fileio, etc. In each <code>__</code>init<code>__</code>.py in these packages, I want to make a test suite consisting of all the tests in all the modules in that package. Of course, getting all th... | 0 | 2009-02-17T05:02:44Z | 555,717 | <p>Solution to exactly this problem from our django project:</p>
<pre><code>"""Test loader for all module tests
"""
import unittest
import re, os, imp, sys
def find_modules(package):
files = [re.sub('\.py$', '', f) for f in os.listdir(os.path.dirname(package.__file__))
if f.endswith(".py")]
retur... | 2 | 2009-02-17T06:37:56Z | [
"python",
"unit-testing",
"module",
"packages",
"python-2.5"
] |
Getting a list of all modules in the current package | 555,571 | <p>Here's what I want to do: I want to build a test suite that's organized into packages like tests.ui, tests.text, tests.fileio, etc. In each <code>__</code>init<code>__</code>.py in these packages, I want to make a test suite consisting of all the tests in all the modules in that package. Of course, getting all th... | 0 | 2009-02-17T05:02:44Z | 555,942 | <p>Good answers here, but the <strong>best</strong> thing to do would be to use a 3rd party test discovery and runner like:</p>
<ul>
<li><a href="http://somethingaboutorange.com/mrl/projects/nose/" rel="nofollow">Nose</a> (my favourite)</li>
<li><a href="http://twistedmatrix.com/trac/wiki/TwistedTrial" rel="nofollow">... | 2 | 2009-02-17T08:36:55Z | [
"python",
"unit-testing",
"module",
"packages",
"python-2.5"
] |
SQLAlchemy/Elixir validation rules? | 555,578 | <p>I just found out how to validate my database input before saving it, but I'm kinda bummed to find there are no premade rules (like validate email, length, etc) that are found in some web based frameworks. Are there any validation libraries laying around anywhere or somewhere that some premade validation lists are hi... | 1 | 2009-02-17T05:06:35Z | 555,893 | <p>Yes. There are. But keep your validation separate from your data layer. (As all the web frameworks do.)</p>
<p>Now the libraries you can use for validation are the exact form libraries from the web frameworks. Start with:</p>
<ul>
<li><a href="http://formencode.org/" rel="nofollow">Formencode</a></li>
</ul>
<p>An... | 3 | 2009-02-17T08:18:18Z | [
"python",
"validation",
"sqlalchemy",
"python-elixir"
] |
Character Translation using Python (like the tr command) | 555,705 | <p>Is there a way to do character translation (kind of like the tr command) using python</p>
| 28 | 2009-02-17T06:33:06Z | 555,724 | <p>See <a href="http://docs.python.org/library/stdtypes.html#str.translate"><code>string.translate</code></a></p>
<pre><code>import string
"abc".translate(string.maketrans("abc", "def")) # => "def"
</code></pre>
<p>Note the doc's comments about subtleties in the translation of unicode strings.</p>
<p>Edit: Since ... | 29 | 2009-02-17T06:40:10Z | [
"python"
] |
Character Translation using Python (like the tr command) | 555,705 | <p>Is there a way to do character translation (kind of like the tr command) using python</p>
| 28 | 2009-02-17T06:33:06Z | 1,385,542 | <p>If you're using python3 translate is less verbose:</p>
<pre><code>>>> 'abc'.translate(str.maketrans('ac','xy'))
'xby'
</code></pre>
<p>Ahh.. and there is also equivalent to <code>tr -d</code>:</p>
<pre><code>>>> "abc".translate(str.maketrans('','','b'))
'ac'
</code></pre>
<p>For <code>tr -d</c... | 14 | 2009-09-06T12:17:56Z | [
"python"
] |
Character Translation using Python (like the tr command) | 555,705 | <p>Is there a way to do character translation (kind of like the tr command) using python</p>
| 28 | 2009-02-17T06:33:06Z | 19,165,983 | <p>A simpler approach may be to use replace. e.g.</p>
<pre><code> "abc".replace("abc", "def")
'def'
</code></pre>
<p>No need to import anything. Works in Python 2.x</p>
| -4 | 2013-10-03T18:00:24Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.