question_id
int64
1.48k
40.1M
title
stringlengths
15
142
question_body
stringlengths
46
12.1k
question_type
stringclasses
5 values
question_date
stringlengths
20
20
1,476
How do you express binary literals in Python?
<p>How do you express an integer as a binary number with Python literals?</p> <p>I was easily able to find the answer for hex:</p> <pre><code> &gt;&gt;&gt; 0x12AF 4783 &gt;&gt;&gt; 0x100 256 </code></pre> <p>and octal:</p> <pre><code> &gt;&gt;&gt; 01267 695 &gt;&gt;&gt; 0100 64 </code></pre> <p><strong>How do you use literals to express binary in Python?</strong></p> <hr> <p><strong><em>Summary of Answers</em></strong></p> <ul> <li>Python 2.5 and earlier: can express binary using <code>int('01010101111',2)</code> but not with a literal.</li> <li>Python 2.5 and earlier: there is <em>no way</em> to express binary literals.</li> <li>Python 2.6 beta: You can do like so: <code>0b1100111</code> or <code>0B1100111</code>.</li> <li>Python 2.6 beta: will also allow <code>0o27</code> or <code>0O27</code> (second character is the letter O) to represent an octal.</li> <li>Python 3.0 beta: Same as 2.6, but will no longer allow the older <code>027</code> syntax for octals.</li> </ul>
howto
2008-08-04T18:20:36Z
1,854
How to check what OS am I running on in Python?
<p>What do I need to look at to see if I'm on Windows, Unix, etc?</p>
howto
2008-08-05T03:23:18Z
3,061
Calling a function of a module from a string with the function's name in Python
<p>What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module <code>foo</code>, and I have a string whose contents are <code>"bar"</code>. What is the best way to go about calling <code>foo.bar()</code>?</p> <p>I need to get the return value of the function, which is why I don't just use <code>eval</code>. I figured out how to do it by using <code>eval</code> to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.</p>
howto
2008-08-06T03:36:08Z
36,139
How do I sort a list of strings in Python?
<p>What is the best way of creating an alphabetically sorted list in Python?</p>
howto
2008-08-30T17:03:09Z
38,987
How to merge two Python dictionaries in a single expression?
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
howto
2008-09-02T07:44:30Z
42,950
Get Last Day of the Month in Python
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
howto
2008-09-04T00:54:44Z
53,513
Best way to check if a list is empty
<p>For example, if passed the following:</p> <pre><code>a = [] </code></pre> <p>How do I check to see if <code>a</code> is empty?</p>
howto
2008-09-10T06:20:11Z
59,825
How to retrieve an element from a set without removing it?
<p>Suppose the following:</p> <pre><code>&gt;&gt;&gt;s = set([1, 2, 3]) </code></pre> <p>How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.</p> <p>Quick and dirty:</p> <pre><code>&gt;&gt;&gt;elem = s.pop() &gt;&gt;&gt;s.add(elem) </code></pre> <p>But do you know of a better way? Ideally in constant time.</p>
howto
2008-09-12T19:58:33Z
70,797
Python: user input and commandline arguments
<p>How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?</p>
howto
2008-09-16T09:44:59Z
73,663
Terminating a Python script
<p>I am aware of the <code>die()</code> command in PHP which stops a script early.</p> <p>How can I do this in Python?</p>
howto
2008-09-16T15:35:55Z
82,831
How do I check whether a file exists using Python?
<p>How do I check whether a file exists, without using the <a href="https://docs.python.org/3.6/reference/compound_stmts.html#try"><code>try</code></a> statement?</p>
howto
2008-09-17T12:55:00Z
89,228
Calling an external command in Python
<p>How can I call an external command (as if I'd typed it at the Unix shell or Windows command prompt) from within a Python script?</p>
howto
2008-09-18T01:35:30Z
100,210
What is the standard way to add N seconds to datetime.time in Python?
<p>Given a <code>datetime.time</code> value in Python, is there a standard way to add an integer number of seconds to it, so that <code>11:34:59</code> + 3 = <code>11:35:02</code>, for example?</p> <p>These obvious ideas don't work:</p> <pre><code>&gt;&gt;&gt; datetime.time(11, 34, 59) + 3 TypeError: unsupported operand type(s) for +: 'datetime.time' and 'int' &gt;&gt;&gt; datetime.time(11, 34, 59) + datetime.timedelta(0, 3) TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta' &gt;&gt;&gt; datetime.time(11, 34, 59) + datetime.time(0, 0, 3) TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time' </code></pre> <p>In the end I have written functions like this:</p> <pre><code>def add_secs_to_time(timeval, secs_to_add): secs = timeval.hour * 3600 + timeval.minute * 60 + timeval.second secs += secs_to_add return datetime.time(secs // 3600, (secs % 3600) // 60, secs % 60) </code></pre> <p>I can't help thinking that I'm missing an easier way to do this though.</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/656297/python-time-timedelta-equivalent">python time + timedelta equivalent</a></li> </ul>
howto
2008-09-19T07:19:36Z
104,420
How to generate all permutations of a list in Python
<p>How do you generate all the permutations of a list in Python, independently of the type of elements in that list?</p> <p>For example:</p> <pre><code>permutations([]) [] permutations([1]) [1] permutations([1, 2]) [1, 2] [2, 1] permutations([1, 2, 3]) [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1] </code></pre> <p>EDIT: Eliben pointed to a solution that's similar to mine although simpler, so I'm choosing it as the accepted answer, although Python 2.6+ has a builtin solution in the <strong>itertools</strong> module:</p> <pre><code>import itertools itertools.permutations([1, 2, 3]) </code></pre>
howto
2008-09-19T18:41:03Z
113,655
Is there a function in python to split a word into a list?
<p>Is there a function in python to split a word into a list of single letters? e.g:</p> <pre><code>s="Word to Split" </code></pre> <p>to get</p> <pre><code>wordlist=['W','o','r','d','','t','o' ....] </code></pre>
howto
2008-09-22T07:40:50Z
118,516
How do I read an Excel file into Python using xlrd? Can it read newer Office formats?
<p>My issue is below but would be interested comments from anyone with experience with xlrd.</p> <p>I just found xlrd and it looks like the perfect solution but I'm having a little problem getting started. I am attempting to extract data programatically from an Excel file I pulled from Dow Jones with current components of the Dow Jones Industrial Average (link: <a href="http://www.djindexes.com/mdsidx/?event=showAverages">http://www.djindexes.com/mdsidx/?event=showAverages</a>)</p> <p>When I open the file unmodified I get a nasty BIFF error (binary format not recognized)</p> <p>However you can see in this screenshot that Excel 2008 for Mac thinks it is in 'Excel 1997-2004' format (screenshot: <a href="http://skitch.com/alok/ssa3/componentreport-dji.xls-properties">http://skitch.com/alok/ssa3/componentreport-dji.xls-properties</a>)</p> <p>If I instead open it in Excel manually and save as 'Excel 1997-2004' format explicitly, then open in python usig xlrd, everything is wonderful. Remember, Office thinks the file is already in 'Excel 1997-2004' format. All files are .xls</p> <p>Here is a pastebin of an ipython session replicating the issue: <a href="http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq">http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq</a></p> <p>Any thoughts on: How to trick xlrd into recognizing the file so I can extract data? How to use python to automate the explicit 'save as' format to one that xlrd will accept? Plan B?</p>
howto
2008-09-23T00:58:09Z
120,656
Directory listing in Python
<p>How do I get a list of all files (and directories) in a given directory in Python?</p>
howto
2008-09-23T12:28:19Z
123,198
How do I copy a file in python?
<p>How do I copy a file in Python? I couldn't find anything under <a href="https://docs.python.org/2/library/os.html"><code>os</code></a>.</p>
howto
2008-09-23T19:23:48Z
163,542
Python - How do I pass a string into subprocess.Popen (using the stdin argument)?
<p>If I do the following:</p> <pre><code>import subprocess from cStringIO import StringIO subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0] </code></pre> <p>I get:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__ (p2cread, p2cwrite, File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles p2cread = stdin.fileno() AttributeError: 'cStringIO.StringI' object has no attribute 'fileno' </code></pre> <p>Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen. How do I work around this?</p>
howto
2008-10-02T17:25:23Z
168,409
How do you get a directory listing sorted by creation date in python?
<p>What is the best way to get a list of all files in a directory, sorted by date [created | modified], using python, on a windows machine?</p>
howto
2008-10-03T19:10:08Z
176,918
Finding the index of an item given a list containing it in Python
<p>For a list <code>["foo", "bar", "baz"]</code> and an item in the list <code>"bar"</code>, what's the cleanest way to get its index (1) in Python?</p>
howto
2008-10-07T01:39:38Z
180,606
How do I convert a list of ascii values to a string in python?
<p>I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values. How do I convert this into a "regular" string that I can echo to the screen?</p>
howto
2008-10-07T21:51:01Z
186,857
Splitting a semicolon-separated string to a dictionary, in Python
<p>I have a string that looks like this:</p> <pre><code>"Name1=Value1;Name2=Value2;Name3=Value3" </code></pre> <p>Is there a built-in class/function in Python that will take that string and construct a dictionary, as though I had done this:</p> <pre><code>dict = { "Name1": "Value1", "Name2": "Value2", "Name3": "Value3" } </code></pre> <p>I have looked through the modules available but can't seem to find anything that matches.</p> <p><hr /></p> <p>Thanks, I do know how to make the relevant code myself, but since such smallish solutions are usually mine-fields waiting to happen (ie. someone writes: Name1='Value1=2';) etc. then I usually prefer some pre-tested function.</p> <p>I'll do it myself then.</p>
howto
2008-10-09T11:38:22Z
187,273
Base-2 (Binary) Representation Using Python
<p>Building on <a href="http://stackoverflow.com/questions/1476/how-do-you-express-binary-literals-in-python#13107">How Do You Express Binary Literals in Python</a>, I was thinking about sensible, intuitive ways to do that Programming 101 chestnut of displaying integers in base-2 form. This is the best I came up with, but I'd like to replace it with a better algorithm, or at least one that should have screaming-fast performance. </p> <pre><code>def num_bin(N, places=8): def bit_at_p(N, p): ''' find the bit at place p for number n ''' two_p = 1 &lt;&lt; p # 2 ^ p, using bitshift, will have exactly one # bit set, at place p x = N &amp; two_p # binary composition, will be one where *both* numbers # have a 1 at that bit. this can only happen # at position p. will yield two_p if N has a 1 at # bit p return int(x &gt; 0) bits = ( bit_at_p(N,x) for x in xrange(places)) return "".join( (str(x) for x in bits) ) # or, more consisely # return "".join([str(int((N &amp; 1 &lt;&lt; x)&gt;0)) for x in xrange(places)]) </code></pre>
howto
2008-10-09T13:38:32Z
187,455
Counting array elements in Python
<p>How can I count the number of elements in an array, because contrary to logic array.count(string) does not count all the elements in the array, it just searches for the number of occurrences of string.</p>
howto
2008-10-09T14:12:55Z
199,059
I'm looking for a pythonic way to insert a space before capital letters
<p>I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word".</p> <p>My limited regex experience just stalled out on me - can someone think of a decent regex to do this, or (better yet) is there a more pythonic way to do this that I'm missing?</p>
howto
2008-10-13T21:16:40Z
200,738
How can I unpack binary hex formatted data in Python?
<p>Using the PHP <a href="http://www.php.net/pack" rel="nofollow">pack()</a> function, I have converted a string into a binary hex representation:</p> <pre><code>$string = md5(time); // 32 character length $packed = pack('H*', $string); </code></pre> <p>The H* formatting means "Hex string, high nibble first".</p> <p>To unpack this in PHP, I would simply use the <a href="http://www.php.net/unpack" rel="nofollow">unpack()</a> function with the H* format flag.</p> <p>How would I unpack this data in Python?</p>
howto
2008-10-14T11:08:07Z
208,894
How to base64 encode a PDF file in Python
<p>How should I base64 encode a PDF file for transport over XML-RPC in Python?</p>
howto
2008-10-16T14:54:49Z
209,513
Convert hex string to int in Python
<p>How do I convert a hex string to an int in Python? </p> <p>I may have it as "<code>0xffff</code>" or just "<code>ffff</code>".</p>
howto
2008-10-16T17:28:03Z
209,840
Map two lists into a dictionary in Python
<p>Imagine that you have:</p> <pre><code>keys = ('name', 'age', 'food') values = ('Monty', 42, 'spam') </code></pre> <p>What is the simplest way to produce the following dictionary ?</p> <pre><code>dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'} </code></pre> <p>This code works, but I'm not really proud of it :</p> <pre><code>dict = {} junk = map(lambda k, v: dict.update({k: v}), keys, values) </code></pre>
howto
2008-10-16T19:05:47Z
227,459
ASCII value of a character in Python
<p>How do I get the <a href="http://en.wikipedia.org/wiki/ASCII">ASCII</a> value of a character as an int in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
howto
2008-10-22T20:39:57Z
227,461
Open file, read it, process, and write back - shortest method in Python
<p>I want to do some basic filtering on a file. Read it, do processing, write it back. </p> <p>I'm not looking for "golfing", but want the simplest and most elegant method to achieve this. I came up with:</p> <pre><code>from __future__ import with_statement filename = "..." # or sys.argv... with open(filename) as f: new_txt = # ...some translation of f.read() open(filename, 'w').write(new_txt) </code></pre> <p>The <code>with</code> statement makes things shorter since I don't have to explicitly open and close the file.</p> <p>Any other ideas ?</p>
howto
2008-10-22T20:40:00Z
234,512
Splitting strings in python
<p>I have a string which is like this:</p> <p>this is [bracket test] "and quotes test "</p> <p>I'm trying to write something in Python to split it up by space while ignoring spaces within square braces and quotes. The result I'm looking for is:</p> <p>['this','is','bracket test','and quotes test '] </p>
howto
2008-10-24T17:33:41Z
237,079
How to get file creation & modification date/times in Python?
<p>I have a script that needs to do some stuff based on file creation &amp; modification dates but has to run on Linux &amp; Windows.</p> <p>What's the best <strong>cross-platform</strong> way to get file creation &amp; modification date/times in Python?</p>
howto
2008-10-25T21:54:56Z
247,724
How can I launch an instance of an application using Python?
<p>I am creating a Python script where it does a bunch of tasks and one of those tasks is to launch and open an instance of Excel. What is the ideal way of accomplishing that in my script?</p>
howto
2008-10-29T17:40:12Z
247,770
Retrieving python module path
<p>I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.</p> <p>How do I retrieve a module's path in python?</p>
howto
2008-10-29T17:52:40Z
251,464
How to get a function name as a string in Python?
<p>In Python, how do I get a function name as a string without calling the function?</p> <pre><code>def my_function(): pass print get_function_name_as_string(my_function) # my_function is not in quotes </code></pre> <p>should output <code>"my_function"</code>.</p> <p>Is this available in python? If not, any idea how to write <code>get_function_name_as_string</code> in Python?</p>
howto
2008-10-30T19:38:24Z
258,746
Slicing URL with Python
<p>I am working with a huge list of URL's. Just a quick question I have trying to slice a part of the URL out, see below:</p> <pre><code>http://www.domainname.com/page?CONTENT_ITEM_ID=1234&amp;param2&amp;param3 </code></pre> <p>How could I slice out:</p> <pre><code>http://www.domainname.com/page?CONTENT_ITEM_ID=1234 </code></pre> <p>Sometimes there is more than two parameters after the CONTENT_ITEM_ID and the ID is different each time, I am thinking it can be done by finding the first &amp; and then slicing off the chars before that &amp;, not quite sure how to do this tho.</p> <p>Cheers</p>
howto
2008-11-03T14:22:13Z
265,960
Best way to strip punctuation from a string in Python
<p>It seems like there should be a simpler way than:</p> <pre><code>import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) </code></pre> <p>Is there?</p>
howto
2008-11-05T17:30:32Z
275,018
How can I remove (chomp) a newline in Python?
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
howto
2008-11-08T18:25:24Z
276,052
How to get current CPU and RAM usage in Python?
<p>What's your preferred way of getting current system status (current CPU, RAM, free disk space, etc.) in Python? Bonus points for *nix and Windows platforms.</p> <p>There seems to be a few possible ways of extracting that from my search:</p> <ol> <li><p>Using a library such as <a href="http://www.psychofx.com/psi/trac/wiki/">PSI</a> (that currently seems not actively developed and not supported on multiple platform) or something like <a href="http://www.i-scream.org/pystatgrab/">pystatgrab</a> (again no activity since 2007 it seems and no support for Windows).</p></li> <li><p>Using platform specific code such as using a <code>os.popen("ps")</code> or similar for the *nix systems and <code>MEMORYSTATUS</code> in <code>ctypes.windll.kernel32</code> (see <a href="http://code.activestate.com/recipes/511491/">this recipe on ActiveState</a>) for the Windows platform. One could put a Python class together with all those code snippets.</p></li> </ol> <p>It's not that those methods are bad but is there already a well-supported, multi-platform way of doing the same thing?</p>
howto
2008-11-09T16:04:50Z
296,499
How do I zip the contents of a folder using python (version 2.5)?
<p>Once I have all the files I require in a particular folder, I would like my python script to zip the folder contents. Is this possible? And how could I go about doing it? A point in the right direction (i.e. a link with an example) or an example that I can see would be extremely helpful. Thanks in advance.</p>
howto
2008-11-17T19:00:07Z
300,445
How to unquote a urlencoded unicode string in python?
<p>I have a unicode string like "Tanım" which is encoded as "Tan%u0131m" somehow. How can i convert this encoded string back to original unicode. Apparently urllib.unquote does not support unicode.</p>
howto
2008-11-18T22:49:27Z
306,400
How do I randomly select an item from a list using Python?
<p>Assume I have the following list:</p> <pre><code>foo = ['a', 'b', 'c', 'd', 'e'] </code></pre> <p>What is the simplest way to retrieve an item at random from this list?</p>
howto
2008-11-20T18:42:21Z
311,627
How to print date in a regular format in Python?
<p>This is my code:</p> <pre><code>import datetime today = datetime.date.today() print today </code></pre> <p>This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:</p> <pre><code>import datetime mylist = [] today = datetime.date.today() mylist.append(today) print mylist </code></pre> <p>This prints the following: </p> <pre><code>[datetime.date(2008, 11, 22)] </code></pre> <p>How on earth can I get just a simple date like "2008-11-22"?</p>
howto
2008-11-22T18:37:07Z
312,443
How do you split a list into evenly sized chunks?
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
howto
2008-11-23T12:15:52Z
317,413
Get Element value with minidom with Python
<p>I am creating a GUI frontend for the Eve Online API in Python.</p> <p>I have successfully pulled the XML data from their server.</p> <p>I am trying to grab the value from a node called "name":</p> <pre><code>from xml.dom.minidom import parse dom = parse("C:\\eve.xml") name = dom.getElementsByTagName('name') print name </code></pre> <p>This seems to find the node, but the output is below:</p> <pre><code>[&lt;DOM Element: name at 0x11e6d28&gt;] </code></pre> <p>How could I get it to print the value of the node?</p>
howto
2008-11-25T13:57:02Z
319,426
How do I do a case insensitive string comparison in Python?
<p>What's the best way to do case insensitive string comparison in Python?</p> <p>I would like to encapsulate comparison of a regular strings to a repository string using in a very simple and pythonic way. I also would like to have ability to look up values in a dict hashed by strings using regular python strings. Much obliged for advice.</p>
howto
2008-11-26T01:06:44Z
324,214
What is the fastest way to parse large XML docs in Python?
<p>I am currently the following code based on Chapter 12.5 of the Python Cookbook:</p> <pre><code>from xml.parsers import expat class Element(object): def __init__(self, name, attributes): self.name = name self.attributes = attributes self.cdata = '' self.children = [] def addChild(self, element): self.children.append(element) def getAttribute(self,key): return self.attributes.get(key) def getData(self): return self.cdata def getElements(self, name=''): if name: return [c for c in self.children if c.name == name] else: return list(self.children) class Xml2Obj(object): def __init__(self): self.root = None self.nodeStack = [] def StartElement(self, name, attributes): element = Element(name.encode(), attributes) if self.nodeStack: parent = self.nodeStack[-1] parent.addChild(element) else: self.root = element self.nodeStack.append(element) def EndElement(self, name): self.nodeStack.pop() def CharacterData(self,data): if data.strip(): data = data.encode() element = self.nodeStack[-1] element.cdata += data def Parse(self, filename): Parser = expat.ParserCreate() Parser.StartElementHandler = self.StartElement Parser.EndElementHandler = self.EndElement Parser.CharacterDataHandler = self.CharacterData ParserStatus = Parser.Parse(open(filename).read(),1) return self.root </code></pre> <p>I am working with XML docs about 1 GB in size. Does anyone know a faster way to parse these?</p>
howto
2008-11-27T16:47:54Z
329,886
In Python, is there a concise way to use a list comprehension with multiple iterators?
<p>Basically, I would like to build a list comprehension over the "cartesian product" of two iterators. Think about the following <a href="http://www.haskell.org/haskellwiki/List_comprehension" rel="nofollow">Haskell code</a>:</p> <pre><code>[(i,j) | i &lt;- [1,2], j &lt;- [1..4]] </code></pre> <p>which yields</p> <pre><code>[(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4)] </code></pre> <p>Can I obtain a similar behavior in Python in a concise way?</p>
howto
2008-12-01T02:44:03Z
348,196
Creating a list of objects in Python
<p>I'm trying to create a Python script that opens several databases and compares their contents. In the process of creating that script, I've run into a problem in creating a list whose contents are objects that I've created.</p> <p>I've simplified the program to its bare bones for this posting. First I create a new class, create a new instance of it, assign it an attribute and then write it to a list. Then I assign a new value to the instance and again write it to a list... and again and again...</p> <p>Problem is, it's always the same object so I'm really just changing the base object. When I read the list, I get a repeat of the same object over and over. </p> <p>So how do you write objects to a list within a loop?</p> <p>Thanks,</p> <p>Bob J</p> <p>Here's my simplified code</p> <pre><code>class SimpleClass(object): pass x = SimpleClass # Then create an empty list simpleList = [] #Then loop through from 0 to 3 adding an attribute to the instance 'x' of SimpleClass for count in range(0,4): # each iteration creates a slightly different attribute value, and then prints it to # prove that step is working # but the problem is, I'm always updating a reference to 'x' and what I want to add to # simplelist is a new instance of x that contains the updated attribute x.attr1= '*Bob* '* count print "Loop Count: %s Attribute Value %s" % (count, x.attr1) simpleList.append(x) print '-'*20 # And here I print out each instance of the object stored in the list 'simpleList' # and the problem surfaces. Every element of 'simpleList' contains the same attribute value y = SimpleClass print "Reading the attributes from the objects in the list" for count in range(0,4): y = simpleList[count] print y.attr1 </code></pre> <p>So how do I (append, extend, copy or whatever) the elements of simpleList so that each entry contains a different instance of the object instead of all pointing to the same one?</p>
howto
2008-12-07T22:15:46Z
354,038
How do I check if a string is a number (float) in Python?
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
howto
2008-12-09T20:03:42Z
359,903
Comparing List of Arguments to it self?
<p>Kind of a weird question, but. I need to have a list of strings i need to make sure that every string in that list is the same.</p> <p>E.g:</p> <pre><code>a = ['foo', 'foo', 'boo'] #not valid b = ['foo', 'foo', 'foo'] #valid </code></pre> <p>Whats the best way to go about doing that?</p> <p>FYI, i don't know how many strings are going to be in the list. Also this is a super easy question, but i am just too tired to think straight.</p>
howto
2008-12-11T16:14:25Z
364,519
In Python, how do I iterate over a dictionary in sorted order?
<p>There's an existing function that ends in:</p> <pre><code>return dict.iteritems() </code></pre> <p>that returns an unsorted iterator for a given dictionary. I would like to return an iterator that goes through the items in sorted order. How do I do that?</p>
howto
2008-12-12T23:57:05Z
367,155
Splitting a string into words and punctuation
<p>I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.</p> <p>For instance:</p> <pre><code>&gt;&gt;&gt; c = "help, me" &gt;&gt;&gt; print c.split() ['help,', 'me'] </code></pre> <p>What I really want the list to look like is:</p> <pre><code>['help', ',', 'me'] </code></pre> <p>So, I want the string split at whitespace with the punctuation split from the words.</p> <p>I've tried to parse the string first and then run the split:</p> <pre><code>&gt;&gt;&gt; for character in c: ... if character in ".,;!?": ... outputCharacter = " %s" % character ... else: ... outputCharacter = character ... separatedPunctuation += outputCharacter &gt;&gt;&gt; print separatedPunctuation help , me &gt;&gt;&gt; print separatedPunctuation.split() ['help', ',', 'me'] </code></pre> <p>This produces the result I want, but is painfully slow on large files.</p> <p>Is there a way to do this more efficiently?</p>
howto
2008-12-14T23:30:33Z
372,102
UTF in Python Regex
<p>I'm aware that Python 3 fixes a lot of UTF issues, I am not however able to use Python 3, I am using 2.5.1</p> <p>I'm trying to regex a document but the document has UTF hyphens in it – rather than -. Python can't match these and if I put them in the regex it throws a wobbly.</p> <p>How can I force Python to use a UTF string or in some way match a character such as that?</p> <p>Thanks for your help</p>
howto
2008-12-16T17:49:12Z
373,459
split string on a number of different characters
<p>I'd like to split a string using one or more separator characters.</p> <p>E.g. "a b.c", split on " " and "." would give the list ["a", "b", "c"].</p> <p>At the moment, I can't see anything in the standard library to do this, and my own attempts are a bit clumsy. E.g.</p> <pre><code>def my_split(string, split_chars): if isinstance(string_L, basestring): string_L = [string_L] try: split_char = split_chars[0] except IndexError: return string_L res = [] for s in string_L: res.extend(s.split(split_char)) return my_split(res, split_chars[1:]) print my_split("a b.c", [' ', '.']) </code></pre> <p>Horrible! Any better suggestions?</p>
howto
2008-12-17T02:06:01Z
379,906
Parse String to Float or Int
<p>In Python, how can I parse a numeric string like <code>"545.2222"</code> to its corresponding float value, <code>542.2222</code>? Or parse the string <code>"31"</code> to an integer, <code>31</code>?</p> <p>I just want to know how to parse a float string to a float, and (separately) an int string to an int.</p>
howto
2008-12-19T01:52:26Z
409,732
Python: Alter elements of a list
<p>I have a list of booleans where occasionally I reset them all to false. After first writing the reset as:</p> <pre><code>for b in bool_list: b = False </code></pre> <p>I found it doesn't work. I spent a moment scratching my head, then remembered that of course it won't work since I'm only changing a reference to the bool, not its value. So I rewrote as:</p> <pre><code>for i in xrange(len(bool_list)): bool_list[i] = False </code></pre> <p>and everything works fine. But I found myself asking, "Is that really the most pythonic way to alter all elements of a list?" Are there other ways that manage to be either more efficient or clearer?</p>
howto
2009-01-03T20:07:28Z
415,511
How to get current time in Python
<p>What is the module/method used to get current time?</p>
howto
2009-01-06T04:54:23Z
432,842
How do you get the logical xor of two variables in Python?
<p>How do you get the <a href="http://en.wikipedia.org/wiki/Exclusive_or">logical xor</a> of two variables in Python?</p> <p>For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):</p> <pre><code>str1 = raw_input("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" </code></pre> <p>The <code>^</code> operator seems to be bitwise, and not defined on all objects:</p> <pre><code>&gt;&gt;&gt; 1 ^ 1 0 &gt;&gt;&gt; 2 ^ 1 3 &gt;&gt;&gt; "abc" ^ "" Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for ^: 'str' and 'str' </code></pre>
howto
2009-01-11T12:34:43Z
436,599
Python Split String
<p>Lets Say we have <code>Zaptoit:685158:[email protected]</code> </p> <p>How do you split so it only be left <code>685158:[email protected]</code></p>
howto
2009-01-12T19:10:57Z
439,115
random Decimal in python
<p>How do I get a random decimal.Decimal? It appears that the random module only returns floats which are a pita to convert to Decimals.</p>
howto
2009-01-13T14:26:49Z
444,058
python - readable list of objects
<p>This is probably a kinda commonly asked question but I could do with help on this. I have a list of class objects and I'm trying to figure out how to make it print an item from that class but rather than desplaying in the;</p> <pre><code>&lt;__main__.evolutions instance at 0x01B8EA08&gt; </code></pre> <p>but instead to show a selected attribute of a chosen object of the class. Can anyone help with that?</p>
howto
2009-01-14T18:07:54Z
444,591
convert a string of bytes into an int (python)
<p>How can I convert a string of bytes into an int in python? </p> <p>Say like this: <code>'y\xcc\xa6\xbb'</code></p> <p>I came up with a clever/stupid way of doing it:</p> <pre><code>sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1])) </code></pre> <p>I know there has to be something builtin or in the standard library that does this more simply...</p> <p>This is different from <a href="http://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python">converting a string of hex digits</a> for which you can use int(xxx, 16), but instead I want to convert a string of actual byte values.</p> <p>UPDATE:</p> <p>I kind of like James' answer a little better because it doesn't require importing another module, but Greg's method is faster:</p> <pre><code>&gt;&gt;&gt; from timeit import Timer &gt;&gt;&gt; Timer('struct.unpack("&lt;L", "y\xcc\xa6\xbb")[0]', 'import struct').timeit() 0.36242198944091797 &gt;&gt;&gt; Timer("int('y\xcc\xa6\xbb'.encode('hex'), 16)").timeit() 1.1432669162750244 </code></pre> <p>My hacky method:</p> <pre><code>&gt;&gt;&gt; Timer("sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1]))").timeit() 2.8819329738616943 </code></pre> <p>FURTHER UPDATE:</p> <p>Someone asked in comments what's the problem with importing another module. Well, importing a module isn't necessarily cheap, take a look:</p> <pre><code>&gt;&gt;&gt; Timer("""import struct\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""").timeit() 0.98822188377380371 </code></pre> <p>Including the cost of importing the module negates almost all of the advantage that this method has. I believe that this will only include the expense of importing it once for the entire benchmark run; look what happens when I force it to reload every time:</p> <pre><code>&gt;&gt;&gt; Timer("""reload(struct)\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""", 'import struct').timeit() 68.474128007888794 </code></pre> <p>Needless to say, if you're doing a lot of executions of this method per one import than this becomes proportionally less of an issue. It's also probably i/o cost rather than cpu so it may depend on the capacity and load characteristics of the particular machine.</p>
howto
2009-01-14T20:46:17Z
455,612
Limiting floats to two decimal points
<p>I want <code>a</code> to be rounded to <em>13.95</em>.</p> <pre><code>&gt;&gt;&gt; a 13.949999999999999 &gt;&gt;&gt; round(a, 2) 13.949999999999999 </code></pre> <p>The <a href="https://docs.python.org/2/library/functions.html#round"><code>round</code></a> function does not work the way I expected.</p>
howto
2009-01-18T18:16:41Z
464,736
Python regular expressions - how to capture multiple groups from a wildcard expression?
<p>I have a Python regular expression that contains a group which can occur zero or many times - but when I retrieve the list of groups afterwards, only the last one is present. Example:</p> <p><code>re.search("(\w)*", "abcdefg").groups</code>()</p> <p>this returns the list ('g',)</p> <p>I need it to return ('a','b','c','d','e','f','g',)</p> <p>Is that possible? How can I do it? </p>
howto
2009-01-21T10:29:31Z
465,144
Tools for creating text as bitmaps (anti-aliased text, custom spacing, transparent background)
<p>I need to batch create images with text. Requirements:</p> <ol> <li>arbitrary size of bitmap</li> <li>PNG format</li> <li>transparent background</li> <li>black text anti-aliased against transparency</li> <li>adjustable character spacing</li> <li>adjustable text position (x and y coordinates where text begins)</li> <li>TrueType and/or Type1 support</li> <li>Unix command line tool or Python library</li> </ol> <p>So far I've evaluated the following:</p> <ul> <li><a href="http://www.pythonware.com/library/pil/" rel="nofollow">Python Imaging Library</a>: fails 5.</li> <li><a href="http://www.imagemagick.org/" rel="nofollow">ImageMagick</a> ("caption" option): hard to figure out 6.</li> <li><a href="http://www.cairographics.org/documentation/pycairo/" rel="nofollow">PyCairo</a>: fails 5.</li> <li><a href="http://www.w3.org/Graphics/SVG/" rel="nofollow">SVG</a> + <a href="http://www.imagemagick.org/script/convert.php" rel="nofollow">ImageMagick convert</a>: most promising, although requires multiple tools</li> </ul> <p>The problem with PIL is that e.g. the default spacing for Verdana is way too sparse. I need the text to be a bit tighter, but there's no way to adjust it in PIL.</p> <p>In ImageMagick I haven't found an easy way to specify where in the image the text begins (I'm using -size WIDTHxHEIGHT and caption:'TEXT'). Adding a transparent border will move the text away from the corner it's achored to, but</p> <ul> <li>image size needs to be adjusted accordingly since border adds to the extents</li> <li>it's not possible to adjust horizontal and vertical offset independently</li> </ul> <p>Have I missed some obvious alternatives or failed to find necessary features from the above mentioned?</p>
howto
2009-01-21T12:45:55Z
466,345
Converting string into datetime
<p>Short and simple. I've got a huge list of date-times like this as strings:</p> <pre><code>Jun 1 2005 1:33PM Aug 28 1999 12:00AM </code></pre> <p>I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects. </p> <p>Any help (even if it's just a kick in the right direction) would be appreciated.</p> <p>Edit: This is going through Django's ORM so I can't use SQL to do the conversion on insert.</p>
howto
2009-01-21T18:00:29Z
498,106
How do I compile a Visual Studio project from the command-line?
<p>I'm scripting the checkout, build, distribution, test, and commit cycle for a large C++ solution that is using <a href="http://en.wikipedia.org/wiki/Monotone_%28software%29">Monotone</a>, <a href="http://en.wikipedia.org/wiki/CMake">CMake</a>, Visual Studio Express 2008, and custom tests. </p> <p>All of the other parts seem pretty straight-forward, but I don't see how to compile the Visual Studio solution without getting the GUI. </p> <p>The script is written in Python, but an answer that would allow me to just make a call to: os.system would do.</p>
howto
2009-01-31T02:52:25Z
508,657
Multidimensional array in Python
<p>I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:</p> <pre><code>double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3]; dArray[0][0][0] = 0; dArray[0][0][1] = POSITIVE_INFINITY; </code></pre> <p>Further values will be created bei loops and written into the array.</p> <p>How do I instantiate the array?</p> <p>PS: There is no matrix multiplication involved...</p>
howto
2009-02-03T19:54:37Z
509,742
Change directory to the directory of a Python script
<p>How do i change directory to the directory with my python script in? So far I figured out I should use <code>os.chdir</code> and <code>sys.argv[0]</code>. I'm sure there is a better way then to write my own function to parse argv[0].</p>
howto
2009-02-04T01:24:43Z
510,348
How can I make a time delay in Python?
<p>I would like to know how to put a time delay in a Python script.</p>
howto
2009-02-04T07:04:09Z
510,357
Python read a single character from the user
<p>Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like <code>getch()</code>). I know there's a function in Windows for it, but I'd like something that is cross-platform.</p>
howto
2009-02-04T07:08:03Z
517,355
String formatting in Python
<p>I want to do something like String.Format ("[{0}, {1}, {2}]", 1, 2, 3) which returns:</p> <pre><code>[1, 2, 3] </code></pre> <p>How do I do this in Python?</p>
howto
2009-02-05T18:53:29Z
519,633
Lazy Method for Reading Big File in Python?
<p>I have a very big file 4GB and when I try to read it my computer hangs. So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.</p> <p>Is there any method to <code>yield</code> these pieces ?</p> <p>I would love to have a <strong>lazy method</strong>.</p>
howto
2009-02-06T09:11:13Z
533,398
In python 2.4, how can I execute external commands with csh instead of bash?
<p>Without using the new 2.6 subprocess module, how can I get either os.popen or os.system to execute my commands using the tcsh instead of bash? I need to source some scripts which are written in tcsh before executing some other commands and I need to do this within python2.4.</p> <p>EDIT Thanks for answers using 'tcsh -c', but I'd like to avoid this because I have to do escape madness. The string will be interpreted by bash and then interpreted by tcsh. I'll have to do something like:</p> <pre><code>os.system("tcsh -c '"+re.compile("'").sub(r"""'"'"'""",my_cmd)+"'") </code></pre> <p>Can't I just tell python to open up a 'tcsh' sub-process instead of a 'bash' subprocess? Is that possible?</p> <p>P.S. I realize that bash is the cat's meow, but I'm working in a corporate environment and I'm going to choose to <em>not</em> fight a tcsh vs bash battle -- bigger fish to fry.</p>
howto
2009-02-10T17:44:23Z
544,923
Switching Printer Trays
<p>I know this question has been asked before, but there was no clear answer. </p> <p>How do I change the printer tray programmatically?</p> <p>I am trying to use python to batch print some PDFs. I need to print different pages from different trays. The printer is a Ricoh 2232C. Is there a way to do it through and Acrobat Reader command line parameter? I am able to use the Win32 api to find out which bins correspond to which binnames, but that is about it. Any advice/shortcuts/etc?</p>
howto
2009-02-13T06:32:56Z
546,321
How do I calculate the date six months from the current date using the datetime Python module?
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
howto
2009-02-13T15:16:25Z
555,344
Match series of (non-nested) balanced parentheses at end of string
<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.photobucket.com/albums/k220/kipper_308/fran_web.jpg" rel="nofollow">no nesting</a>), and the parenthetical expressions may be separated by whitespace.</p> <p>It's harder than it might seem at first glance, at least so it seems to me.</p>
howto
2009-02-17T02:29:03Z
572,263
How do I create a Django form that displays a checkbox label to the right of the checkbox?
<p>When I define a Django form class similar to this:</p> <pre><code>def class MyForm(forms.Form): check = forms.BooleanField(required=True, label="Check this") </code></pre> <p>It expands to HTML that looks like this:</p> <pre><code>&lt;form action="." id="form" method=POST&gt; &lt;p&gt;&lt;label for="check"&gt;Check this:&lt;/label&gt; &lt;input type="checkbox" name="check" id="check" /&gt;&lt;/p&gt; &lt;p&gt;&lt;input type=submit value="Submit"&gt;&lt;/p&gt; &lt;/form&gt; </code></pre> <p>I would like the checkbox input element to have a label that follows the checkbox, not the other way around. Is there a way to convince Django to do that?</p> <p><strong>[Edit]</strong></p> <p>Thanks for the answer from Jonas - still, while it fixes the issue I asked about (checkbox labels are rendered to the right of the checkbox) it introduces a new problem (all widget labels are rendered to the right of their widgets...)</p> <p>I'd like to avoid overriding _html_output() since it's obviously not designed for it. The design I would come up with would be to implement a field html output method in the Field classes, override the one for the Boolean field and use that method in _html_output(). Sadly, the Django developers chose to go a different way, and I would like to work within the existing framework as much as possible. </p> <p>CSS sounds like a decent approach, except that I don't know enough CSS to pull this off or even to decide whether I like this approach or not. Besides, I prefer markup that still resembles the final output, at least in rendering order.</p> <p>Furthermore, since it can be reasonable to have more than one style sheet for any particular markup, doing this in CSS could mean having to do it multiple times for multiple styles, which pretty much makes CSS the wrong answer. </p> <p><strong>[Edit]</strong></p> <p>Seems like I'm answering my own question below. If anyone has a better idea how to do this, don't be shy.</p>
howto
2009-02-21T04:18:17Z
577,234
Python "extend" for a dictionary
<p>Which is the best way to extend a dictionary with another one? For instance:</p> <pre><code>&gt;&gt;&gt; a = { "a" : 1, "b" : 2 } &gt;&gt;&gt; b = { "c" : 3, "d" : 4 } &gt;&gt;&gt; a {'a': 1, 'b': 2} &gt;&gt;&gt; b {'c': 3, 'd': 4} </code></pre> <p>I'm looking for any operation to obtain this avoiding <code>for</code> loop:</p> <pre><code>{ "a" : 1, "b" : 2, "c" : 3, "d" : 4 } </code></pre> <p>I wish to do something like:</p> <pre><code>a.extend(b) # This does not work </code></pre>
howto
2009-02-23T10:59:32Z
579,856
What's the Pythonic way to combine two sequences into a dictionary?
<p>Is there a more concise way of doing this in Python?:</p> <pre><code>def toDict(keys, values): d = dict() for k,v in zip(keys, values): d[k] = v return d </code></pre>
howto
2009-02-23T23:33:26Z
582,723
How to import classes defined in __init__.py
<p>I am trying to organize some modules for my own use. I have something like this:</p> <pre><code>lib/ __init__.py settings.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py </code></pre> <p>In <code>lib/__init__.py</code>, I want to define some classes to be used if I import lib. However, I can't seem to figure it out without separating the classes into files, and import them in<code> __init__.py</code>. </p> <p>Rather than say:</p> <pre><code> lib/ __init__.py settings.py helperclass.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py from lib.settings import Values from lib.helperclass import Helper </code></pre> <p>I want something like this:</p> <pre><code> lib/ __init__.py #Helper defined in this file settings.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py from lib.settings import Values from lib import Helper </code></pre> <p>Is it possible, or do I have to separate the class into another file?</p> <h2>EDIT</h2> <p>OK, if I import lib from another script, I can access the Helper class. How can I access the Helper class from settings.py?</p> <p>The example <a href="http://docs.python.org/tutorial/modules.html">here</a> describes Intra-Package References. I quote "submodules often need to refer to each other". In my case, the lib.settings.py needs the Helper and lib.foo.someobject need access to Helper, so where should I define the Helper class?</p>
howto
2009-02-24T17:35:55Z
587,345
Python regular expression matching a multiline block of text
<p>I'm having a bit of trouble getting a Python regex to work when matching against text that spans multiple lines. The example text is ('\n' is a newline)</p> <pre><code>some Varying TEXT\n \n DSJFKDAFJKDAFJDSAKFJADSFLKDLAFKDSAF\n [more of the above, ending with a newline]\n [yep, there is a variable number of lines here]\n \n (repeat the above a few hundred times). </code></pre> <p>I'd like to capture two things: the 'some_Varying_TEXT' part, and all of the lines of uppercase text that comes two lines below it in one capture (i can strip out the newline characters later). I've tried with a few approaches:</p> <pre><code>re.compile(r"^&gt;(\w+)$$([.$]+)^$", re.MULTILINE) # try to capture both parts re.compile(r"(^[^&gt;][\w\s]+)$", re.MULTILINE|re.DOTALL) # just textlines </code></pre> <p>and a lot of variations hereof with no luck. The last one seems to match the lines of text one by one, which is not what I really want. I can catch the first part, no problem, but I can't seem to catch the 4-5 lines of uppercase text. I'd like match.group(1) to be some&#95;Varying&#95;Text and group(2) to be line1+line2+line3+etc until the empty line is encountered.</p> <p>If anyone's curious, its supposed to be a sequence of aminoacids that make up a protein.</p>
howto
2009-02-25T19:00:49Z
610,883
How to know if an object has an attribute in Python
<p>Is there a way in Python to determine if an object has some attribute? For example:</p> <pre><code>&gt;&gt;&gt; a = SomeClass() &gt;&gt;&gt; a.someProperty = value &gt;&gt;&gt; a.property Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: SomeClass instance has no attribute 'property' </code></pre> <p>How can you tell if <code>a</code> has the attribute <code>property</code> before using it?</p>
howto
2009-03-04T14:45:59Z
613,183
Sort a Python dictionary by value
<p>I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.</p> <p>I can sort on the keys, but how can I sort based on the values?</p> <p>Note: I have read Stack Overflow question <a href="http://stackoverflow.com/questions/72899">How do I sort a list of dictionaries by values of the dictionary in Python?</a> and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.</p>
howto
2009-03-05T00:49:05Z
627,435
How to remove an element from a list by index in Python?
<p>How to remove an element from a list by index in Python?</p> <p>I found the <code>list.remove</code> method, but say I want to remove the last element, how do I do this? It seems like the default remove searches the list, but I don't want any search to be performed.</p>
howto
2009-03-09T18:16:11Z
638,360
Python - How to calculate equal parts of two dictionaries?
<p>I have a problem with combining or calculating common/equal part of these two dictionaries. In my dictionaries, values are lists: </p> <pre><code>d1 = {0:['11','18','25','38'], 1:['11','18','25','38'], 2:['11','18','25','38'], 3:['11','18','25','38']} d2 = {0:['05','08','11','13','16','25','34','38','40', '43'], 1:['05', '08', '09','13','15','20','32','36','38', '40','41'], 2:['02', '08', '11', '13', '18', '20', '22','33','36','39'], 3:['06', '11', '12', '25', '26', '27', '28', '30', '31', '37']} </code></pre> <p>I'd like to check "d2" and know if there are numbers from "d1". If there are some, I'd like to update one of them with new data or receive 3rd dictionary "d3" with only the values that are identical/equal in both "d1" and "d2" like:</p> <pre><code>d3 = {0:['11','25','38'], 1:['38'], 2:['11','18'], 3:['11','25']} </code></pre> <p>Can anyone help me with this?</p> <p>My fault I forgot to be more specific. I'm looking for a solution in Python.</p>
howto
2009-03-12T12:15:14Z
640,001
How can I remove text within parentheses with a regex?
<p>I'm trying to handle a bunch of files, and I need to alter then to remove extraneous information in the filenames; notably, I'm trying to remove text inside parentheses. For example:</p> <pre><code>filename = "Example_file_(extra_descriptor).ext" </code></pre> <p>and I want to regex a whole bunch of files where the parenthetical expression might be in the middle or at the end, and of variable length.</p> <p>What would the regex look like? Perl or Python syntax would be preferred.</p>
howto
2009-03-12T18:56:57Z
645,864
Changing prompt working directory via Python script
<p>Is it possible to change the Windows command prompt working directory via Python script?</p> <p>e.g.</p> <pre><code>&gt;&gt; cd &gt;&gt; c:\windows\system32 &gt;&gt; make_decision_change_dir.py &gt;&gt; cd &gt;&gt; c:\windows </code></pre> <p>I have tried a few things which don't work:</p> <pre><code>import os os.chdir(path) </code></pre> <p><hr /></p> <pre><code>import os, subprocess subprocess.Popen("chdir /D \"%s\"" %path, shell=True) </code></pre> <p><hr /></p> <pre><code>import os, subprocess subprocess.Popen("cd \"%s\"" %path, shell=True) </code></pre> <p><hr /></p> <pre><code>import os, subprocess subprocess.Popen("CD=\"%s\"" %path, shell=True) </code></pre> <p>As I understand it and observe these operations change the current processes working directory - which is the Python process and not the prompt its executing from.</p> <p>Thanks.</p> <p>UPDATE</p> <p>The path I would want to change to is dynamic (based on what project I am working on, the full path to a build location changes) hence I wanted to code a solution in Python rather than hack around with a Windows batch file.</p> <p>UPDATE</p> <p>I ended up hacking a batch file together to do this ;( Thanks everyone.</p>
howto
2009-03-14T12:45:32Z
647,515
How can I know python's path under windows?
<p>I want to know where is the python's installation path. For example:</p> <p>C:\Python25</p> <p>But however, I have no idea how to do. How can I get the installation path of python?</p> <p>Thanks.</p>
howto
2009-03-15T09:09:18Z
652,291
sorting a list of dictionary values by date in python
<p>I have a list and I am appending a dictionary to it as I loop through my data...and I would like to sort by one of the dictionary keys.</p> <p>ex: </p> <pre><code>data = "data from database" list = [] for x in data: dict = {'title':title, 'date': x.created_on} list.append(dict) </code></pre> <p>I want to sort the list in reverse order by value of 'date'</p>
howto
2009-03-16T21:56:51Z
663,171
Is there a way to substring a string in Python?
<p>Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?</p> <p>Maybe like <code>myString[2:end]</code>?</p> <p>If leaving the second part means 'till the end', if you leave the first part, does it start from the start?</p>
howto
2009-03-19T17:29:41Z
674,509
How do I iterate over a Python dictionary, ordered by values?
<p>I've got a dictionary like:</p> <pre><code>{ 'a': 6, 'b': 1, 'c': 2 } </code></pre> <p>I'd like to iterate over it <em>by value</em>, not by key. In other words:</p> <pre><code>(b, 1) (c, 2) (a, 6) </code></pre> <p>What's the most straightforward way?</p>
howto
2009-03-23T17:55:11Z
674,519
How can I convert a Python dictionary to a list of tuples?
<p>If I have a dictionary like:</p> <pre><code>{ 'a': 1, 'b': 2, 'c': 3 } </code></pre> <p>How can I convert it to this?</p> <pre><code>[ ('a', 1), ('b', 2), ('c', 3) ] </code></pre> <p>And how can I convert it to this?</p> <pre><code>[ (1, 'a'), (2, 'b'), (3, 'c') ] </code></pre>
howto
2009-03-23T17:58:32Z
674,764
Examples for string find in Python
<p>I am trying to find some examples but no luck. Does anyone know of some examples on the net? I would like to know what it returns when it can't find, and how to specify from start to end, which I guess is going to be 0, -1.</p>
howto
2009-03-23T18:57:43Z
677,656
How to extract from a list of objects a list of specific attribute?
<p>I have a list of objects. Object has 3 string attributes. I want to make a list containing only a specific attribute from class.</p> <p>Is there any built-in functions to do that?</p>
howto
2009-03-24T14:31:43Z
682,504
What is a clean, pythonic way to have multiple constructors in Python?
<p>I can't find a definitive answer for this. AFAIK, you can't have multiple <code>__init__</code> functions in a Python class. So what is a good way to solve this problem? </p> <p>Suppose I have an class called <code>Cheese</code> with the <code>number_of_holes</code> property. How can I have two ways of creating cheese-objects...</p> <ul> <li>one that takes a number of holes like this: <code>parmesan = Cheese(num_holes = 15)</code></li> <li>and one that takes no arguments and just randomizes the <code>number_of_holes</code> property: <code>gouda = Cheese()</code></li> </ul> <p>I can think of only one way to do this, but that seems kinda clunky:</p> <pre><code>class Cheese(): def __init__(self, num_holes = 0): if (num_holes == 0): # randomize number_of_holes else: number_of_holes = num_holes </code></pre> <p>What do you say? Is there a better way?</p>
howto
2009-03-25T17:00:21Z
687,295
How do I do a not equal in Django queryset filtering?
<p>In Django model QuerySets, I see that there is a <code>__gt</code> and <code>__lt</code> for comparitive values, but is there a <code>__ne</code>/<code>!=</code>/<code>&lt;&gt;</code> (<strong>not equals</strong>?)</p> <p>I want to filter out using a not equals:</p> <p>Example:</p> <pre><code>Model: bool a; int x; </code></pre> <p>I want</p> <pre><code>results = Model.objects.exclude(a=true, x!=5) </code></pre> <p>The <code>!=</code> is not correct syntax. I tried <code>__ne</code>, <code>&lt;&gt;</code>.</p> <p>I ended up using:</p> <pre><code>results = Model.objects.exclude(a=true, x__lt=5).exclude(a=true, x__gt=5) </code></pre>
howto
2009-03-26T19:47:45Z