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 |
|---|---|---|---|---|---|---|---|---|---|
Various Python datetime issues
| 513,291
|
<p>I have two methods that I'm using as custom tags in a template engine:</p>
<pre><code># Renders a <select> form field
def select_field(options, selected_item, field_name):
options = [(str(v),str(v)) for v in options]
html = ['<select name="%s">' % field_name]
for k,v in options:
tmp = '<option '
if k == selected_item:
tmp += 'selected '
tmp += 'value="%s">%s</option>' % (k,v)
html.append(tmp)
html.append('</select>')
return '\n'.join(html)
# Renders a collection of <select> fields for datetime values
def datetime_field(current_dt, field_name):
if current_dt == None:
current_dt = datetime.datetime.now()
day = select_field(range(1, 32), current_dt.day, field_name + "_day")
month = select_field(range(1, 13), current_dt.month, field_name + "_month")
year = select_field(range(datetime.datetime.now().year, datetime.datetime.now().year + 10), current_dt.year, field_name + "_year")
hour = select_field(range(1, 13), current_dt.hour, field_name + "_hour")
minute = select_field(range(1, 60), current_dt.minute, field_name + "_minute")
period = select_field(['AM', 'PM'], 'AM', field_name + "_period")
return "\n".join([day, '/', month, '/', year, ' at ', hour, ':', minute, period])
</code></pre>
<p>As you can see in the comments, I'm attempting to generate select fields for building a date and time value.</p>
<p>My first question is, how do I make the day, month, hour, and minute ranges use two digits? For example, the code generates "1, 2, 3..." while I would like "01, 02, 03".</p>
<p>Next, when the fields get generated, the values of the supplied datetime are not selected automatically, even though I'm telling the select_field method to add a "selected" attribute when the value is equal to the supplied datetime's value.</p>
<p>Finally, how do I get the 12-hour period identifier (AM/PM) for the supplied datetime? For the moment, I'm simply selecting 'AM' by default, but I would like to supply this value from the datetime itself.</p>
| 2
|
2009-02-04T20:54:50Z
| 513,416
|
<p>To add to my previous answer, some comments on making the selected option selected. </p>
<p>First, your HTML generation code would be more robust if rather than splitting the start and end of the HTML tags...</p>
<pre><code>html = ['<select name="%s">' % field_name]
for k,v in options:
tmp = '<option '
if k == selected_item:
tmp += 'selected '
tmp += 'value="%s">%s</option>' % (k,v)
html.append(tmp)
html.append('</select>')
</code></pre>
<p>... you generated them as atomic wholes:</p>
<pre><code>opt_bits = ('<option %s value="%s">'% (['','selected'][str(v)==selected_item], str(v)) for v in options)
# If running Python2.5, it's better to use: 'selected' if str(v)==selected_item else ''
html = '<select name=%s>%s</select>' % '\n'.join(opt_bits)
</code></pre>
<p>Second, I'm not sure why you double the options list rather than reusing the same variable name, as I did above:</p>
<pre><code>options = [(str(v),str(v)) for v in options] # ????
</code></pre>
<p>This is unnecessary, unless options is really a dict and you intended something like:</p>
<pre><code>[ (k,v) for k,v in options.iteritems() ]
</code></pre>
<p>Finally, your code will break if the list items contain quotes. Look in the Python documentation for standard functions for escaping HTML.</p>
<p>Good luck!</p>
| 1
|
2009-02-04T21:22:05Z
|
[
"python",
"datetime"
] |
Newline characters in non ASCII encoded files
| 513,675
|
<p>I'm using Python 2.6 to read latin2 encoded file with windows line endings ('\r\n').</p>
<pre><code>import codecs
file = codecs.open('stackoverflow_secrets.txt', encoding='latin2', mode='rt')
line = file.readline()
print(repr(line))
</code></pre>
<p>outputs : <code>u'login: yabcok\n'</code></p>
<pre><code>file = codecs.open('stackoverflow_secrets.txt', encoding='latin2', mode='r')
line = file.readline()
print(repr(line))
</code></pre>
<p>or</p>
<pre><code>file = codecs.open('stackoverflow_secrets.txt', encoding='latin2', mode='rb')
line = file.readline()
print(repr(line))
</code></pre>
<p>outputs : <code>u'password: l1x1%Dm\r\n'</code></p>
<p>My questions:</p>
<ol>
<li>Why text mode is not the default? Documentation states otherwise. Is <code>codecs</code> module commonly used with binary files?</li>
<li>Why newline chars aren't stripped from readline() output? This is annoying and redundant.</li>
<li>Is there a way to specify newline character for files not ASCII encoded.</li>
</ol>
| 1
|
2009-02-04T22:28:09Z
| 513,820
|
<p>Are you sure that your examples are correct? The <a href="http://docs.python.org/library/codecs.html#module-codecs" rel="nofollow">documentation</a> of the codecs module says: </p>
<blockquote>
<p>Note: Files are always opened in binary mode, even if no binary mode was specified. This is done to avoid data loss due to encodings using 8-bit values. This means that no automatic conversion of '\n' is done on reading and writing.</p>
</blockquote>
<p>On my system, with a Latin-2 encoded file + DOS line endings, there's no difference between "rt", "r" and "rb" (Disclaimer: I'm using 2.5 on Linux).</p>
<p>The documentation for <code>open</code> also mentions no "t" flag, so that behavior seems a little strange. </p>
<p>Newline characters are not stripped from lines because not all lines returned by <code>readline</code> may end in newlines. If the file does not end with a newline, the last line does not carry one. (I obviously can't come up with a better explanation).</p>
<p>Newline characters do not differ based on the encoding (at least not among the ones which use ASCII for 0-127), only based on the platform. You can specify "U" in the mode when opening the file and Python will detect any form of newline, either Windows, Mac or Unix.</p>
| 4
|
2009-02-04T23:13:09Z
|
[
"python",
"encoding",
"file"
] |
Newline characters in non ASCII encoded files
| 513,675
|
<p>I'm using Python 2.6 to read latin2 encoded file with windows line endings ('\r\n').</p>
<pre><code>import codecs
file = codecs.open('stackoverflow_secrets.txt', encoding='latin2', mode='rt')
line = file.readline()
print(repr(line))
</code></pre>
<p>outputs : <code>u'login: yabcok\n'</code></p>
<pre><code>file = codecs.open('stackoverflow_secrets.txt', encoding='latin2', mode='r')
line = file.readline()
print(repr(line))
</code></pre>
<p>or</p>
<pre><code>file = codecs.open('stackoverflow_secrets.txt', encoding='latin2', mode='rb')
line = file.readline()
print(repr(line))
</code></pre>
<p>outputs : <code>u'password: l1x1%Dm\r\n'</code></p>
<p>My questions:</p>
<ol>
<li>Why text mode is not the default? Documentation states otherwise. Is <code>codecs</code> module commonly used with binary files?</li>
<li>Why newline chars aren't stripped from readline() output? This is annoying and redundant.</li>
<li>Is there a way to specify newline character for files not ASCII encoded.</li>
</ol>
| 1
|
2009-02-04T22:28:09Z
| 514,168
|
<blockquote>
<p>mode='rt'</p>
</blockquote>
<p>'rt' isn't a real mode as such - that will do the same as 'r'. </p>
<blockquote>
<p>Why text mode is not the default?</p>
</blockquote>
<p>See Torsten's answer.</p>
<p>Also, if you are using anything but Windows, text mode files behave identically to binary files anyway.</p>
<p>You may instead be thinking of 'U'niversal newlines mode, which attempts to allow other platforms' text-mode files to work. Whilst it is possible to pass a 'U' flag to codecs.open, given the doc as outlined above I think it's <a href="http://bugs.python.org/issue691291" rel="nofollow">bug</a>. Certainly the results would go wrong on UTF-16 and some East Asian codecs, so don't rely on it.</p>
<blockquote>
<p>Why newline chars aren't stripped from readline() output?</p>
</blockquote>
<p>It is necessary to be able to tell whether the last line of the file ends with a trailing newline.</p>
| 1
|
2009-02-05T01:23:09Z
|
[
"python",
"encoding",
"file"
] |
Delete file from zipfile with the ZipFile Module
| 513,788
|
<p>The only way i came up for deleting a file from a zipfile was to create a temporary zipfile without the file to be deleted and then rename it to the original filename.</p>
<p>In python 2.4 the ZipInfo class had an attribute <code>file_offset</code>, so it was possible to create a second zip file and copy the data to other file without decompress/recompressing.</p>
<p>This <code>file_offset</code> is missing in python 2.6, so is there another option than creating another zipfile by uncompressing every file and then recompressing it again?</p>
<p>Is there maybe a direct way of deleting a file in the zipfile, i searched and didn't find anything.</p>
<p>Thanks in advance.</p>
| 22
|
2009-02-04T23:00:26Z
| 513,889
|
<p>The following snippet worked for me (deletes all *.exe files from a Zip archive):</p>
<pre><code>zin = zipfile.ZipFile ('archive.zip', 'r')
zout = zipfile.ZipFile ('archve_new.zip', 'w')
for item in zin.infolist():
buffer = zin.read(item.filename)
if (item.filename[-4:] != '.exe'):
zout.writestr(item, buffer)
zout.close()
zin.close()
</code></pre>
<p>If you read everything into memory, you can eliminate the need for a second file. However, this snippet recompresses everything.</p>
<p>After closer inspection the <code>ZipInfo.header_offset</code> is the offset from the file start. The name is misleading, but the main Zip header is actually stored at the end of the file. My hex editor confirms this.</p>
<p>So the problem you'll run into is the following: You need to delete the directory entry in the main header as well or it will point to a file that doesn't exist anymore. Leaving the main header intact might work if you keep the local header of the file you're deleting as well, but I'm not sure about that. How did you do it with the old module?</p>
<p>Without modifying the main header I get an error "missing X bytes in zipfile" when I open it. <a href="http://www.pkware.com/documents/casestudies/APPNOTE.TXT">This</a> might help you to find out how to modify the main header.</p>
| 28
|
2009-02-04T23:31:37Z
|
[
"python",
"zip"
] |
How to distribute script using gdata-python-client?
| 513,806
|
<p>I've written several scripts that make use of the gdata API, and they all (obviously) have my API key and client ID in plain-text. How am I supposed to distribute these?</p>
| 3
|
2009-02-04T23:06:11Z
| 513,829
|
<p>Move the variables into a separate module and replace your values with dummy values. Make sure you trap for an invalid key and provide instructions on how to obtain a key and where to place it. In your code you can just import the values from that module.</p>
<pre><code>import gdata_api_key
print gdata_api_key.key_value
</code></pre>
| 3
|
2009-02-04T23:16:32Z
|
[
"python",
"gdata-api"
] |
How to distribute script using gdata-python-client?
| 513,806
|
<p>I've written several scripts that make use of the gdata API, and they all (obviously) have my API key and client ID in plain-text. How am I supposed to distribute these?</p>
| 3
|
2009-02-04T23:06:11Z
| 513,838
|
<p>If we assume that you want clients to use their own keys I'd recommend putting them in a configuration file which defaults to an (invalid) sentinel value.</p>
<p>If on the other hand you want the script to use your key the best you can do is obfuscate it. After all, if your program can read it then an attacker (with a debugger) can read it too.</p>
| 0
|
2009-02-04T23:18:05Z
|
[
"python",
"gdata-api"
] |
Python: List vs Dict for look up table
| 513,882
|
<p>I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a <i>list</i> or <i>dict</i>?</p>
<p>I know you can do something like this for both:</p>
<pre><code>if something in dict_of_stuff:
pass
</code></pre>
<p>and</p>
<pre><code>if something in list_of_stuff:
pass
</code></pre>
<p>My thought is the dict will be faster and more efficient.</p>
<p>Thanks for your help.</p>
<p><b>EDIT 1</b> <br>
Little more info on what I'm trying to do. <a href="http://projecteuler.net/index.php?section=problems&id=92">Euler Problem 92</a>. I'm making a look up table to see if a value calculated has all ready been calculated. </p>
<p><b>EDIT 2</b> <br>
Efficiency for look up.</p>
<p><b>EDIT 3</b> <br>
There are no values assosiated with the value...so would a <i>set</i> be better?</p>
| 79
|
2009-02-04T23:28:41Z
| 513,886
|
<p>if data are unique set() will be the most efficient, but of two - dict (which also requires uniqueness, oops :)</p>
| 6
|
2009-02-04T23:30:48Z
|
[
"python",
"performance"
] |
Python: List vs Dict for look up table
| 513,882
|
<p>I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a <i>list</i> or <i>dict</i>?</p>
<p>I know you can do something like this for both:</p>
<pre><code>if something in dict_of_stuff:
pass
</code></pre>
<p>and</p>
<pre><code>if something in list_of_stuff:
pass
</code></pre>
<p>My thought is the dict will be faster and more efficient.</p>
<p>Thanks for your help.</p>
<p><b>EDIT 1</b> <br>
Little more info on what I'm trying to do. <a href="http://projecteuler.net/index.php?section=problems&id=92">Euler Problem 92</a>. I'm making a look up table to see if a value calculated has all ready been calculated. </p>
<p><b>EDIT 2</b> <br>
Efficiency for look up.</p>
<p><b>EDIT 3</b> <br>
There are no values assosiated with the value...so would a <i>set</i> be better?</p>
| 79
|
2009-02-04T23:28:41Z
| 513,890
|
<p>A dict is a hash table, so it is really fast to find the keys. So between dict and list, dict would be faster. But if you don't have a value to associate, it is even better to use a set. It is a hash table, without the "table" part.</p>
<p><hr /></p>
<p>EDIT: for your new question, YES, a set would be better. Just create 2 sets, one for sequences ended in 1 and other for the sequences ended in 89. I have sucessfully solved this problem using sets.</p>
| 28
|
2009-02-04T23:31:41Z
|
[
"python",
"performance"
] |
Python: List vs Dict for look up table
| 513,882
|
<p>I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a <i>list</i> or <i>dict</i>?</p>
<p>I know you can do something like this for both:</p>
<pre><code>if something in dict_of_stuff:
pass
</code></pre>
<p>and</p>
<pre><code>if something in list_of_stuff:
pass
</code></pre>
<p>My thought is the dict will be faster and more efficient.</p>
<p>Thanks for your help.</p>
<p><b>EDIT 1</b> <br>
Little more info on what I'm trying to do. <a href="http://projecteuler.net/index.php?section=problems&id=92">Euler Problem 92</a>. I'm making a look up table to see if a value calculated has all ready been calculated. </p>
<p><b>EDIT 2</b> <br>
Efficiency for look up.</p>
<p><b>EDIT 3</b> <br>
There are no values assosiated with the value...so would a <i>set</i> be better?</p>
| 79
|
2009-02-04T23:28:41Z
| 513,903
|
<p>You want a dict. </p>
<p>For (unsorted) lists in Python, the "in" operation requires O(n) time---not good when you have a large amount of data. A dict, on the other hand, is a hash table, so you can expect O(1) lookup time. </p>
<p>As others have noted, you might choose a set (a special type of dict) instead, if you only have keys rather than key/value pairs.</p>
<p>Related:</p>
<ul>
<li><a href="http://wiki.python.org/moin/TimeComplexity" rel="nofollow">Python wiki</a>: information on the time complexity of Python container operations.</li>
<li><a href="http://stackoverflow.com/questions/45228/where-can-i-find-the-time-and-memory-efficencies-of-the-built-in-sequence-types-i">SO</a>: Python container operation time and memory complexities</li>
</ul>
| 4
|
2009-02-04T23:37:45Z
|
[
"python",
"performance"
] |
Python: List vs Dict for look up table
| 513,882
|
<p>I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a <i>list</i> or <i>dict</i>?</p>
<p>I know you can do something like this for both:</p>
<pre><code>if something in dict_of_stuff:
pass
</code></pre>
<p>and</p>
<pre><code>if something in list_of_stuff:
pass
</code></pre>
<p>My thought is the dict will be faster and more efficient.</p>
<p>Thanks for your help.</p>
<p><b>EDIT 1</b> <br>
Little more info on what I'm trying to do. <a href="http://projecteuler.net/index.php?section=problems&id=92">Euler Problem 92</a>. I'm making a look up table to see if a value calculated has all ready been calculated. </p>
<p><b>EDIT 2</b> <br>
Efficiency for look up.</p>
<p><b>EDIT 3</b> <br>
There are no values assosiated with the value...so would a <i>set</i> be better?</p>
| 79
|
2009-02-04T23:28:41Z
| 513,906
|
<h1>Speed</h1>
<p>Lookups in lists are O(n), lookups in dictionaries are amortized O(1), with regard to the number of items in the data structure. If you don't need to associate values, use sets.</p>
<h1>Memory</h1>
<p>Both dictionaries and sets use hashing and they use much more memory than only for object storage. According to A.M. Kuchling in <em>Beautiful Code</em>, the implementation tries to keep the hash 2/3 full, so you might waste quite some memory. </p>
<p>If you do not add new entries on the fly (which you do, based on your updated question), it might be worthwhile to sort the list and use binary search. This is O(log n), and is likely to be slower for strings, impossible for objects which do not have a natural ordering.</p>
| 109
|
2009-02-04T23:38:36Z
|
[
"python",
"performance"
] |
Python: List vs Dict for look up table
| 513,882
|
<p>I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a <i>list</i> or <i>dict</i>?</p>
<p>I know you can do something like this for both:</p>
<pre><code>if something in dict_of_stuff:
pass
</code></pre>
<p>and</p>
<pre><code>if something in list_of_stuff:
pass
</code></pre>
<p>My thought is the dict will be faster and more efficient.</p>
<p>Thanks for your help.</p>
<p><b>EDIT 1</b> <br>
Little more info on what I'm trying to do. <a href="http://projecteuler.net/index.php?section=problems&id=92">Euler Problem 92</a>. I'm making a look up table to see if a value calculated has all ready been calculated. </p>
<p><b>EDIT 2</b> <br>
Efficiency for look up.</p>
<p><b>EDIT 3</b> <br>
There are no values assosiated with the value...so would a <i>set</i> be better?</p>
| 79
|
2009-02-04T23:28:41Z
| 578,885
|
<p>You don't actually need to store 10 million values in the table, so it's not a big deal either way.</p>
<p>Hint: think about how large your result can be after the first sum of squares operation. The largest possible result will be much smaller than 10 million...</p>
| 1
|
2009-02-23T19:03:30Z
|
[
"python",
"performance"
] |
Python: List vs Dict for look up table
| 513,882
|
<p>I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a <i>list</i> or <i>dict</i>?</p>
<p>I know you can do something like this for both:</p>
<pre><code>if something in dict_of_stuff:
pass
</code></pre>
<p>and</p>
<pre><code>if something in list_of_stuff:
pass
</code></pre>
<p>My thought is the dict will be faster and more efficient.</p>
<p>Thanks for your help.</p>
<p><b>EDIT 1</b> <br>
Little more info on what I'm trying to do. <a href="http://projecteuler.net/index.php?section=problems&id=92">Euler Problem 92</a>. I'm making a look up table to see if a value calculated has all ready been calculated. </p>
<p><b>EDIT 2</b> <br>
Efficiency for look up.</p>
<p><b>EDIT 3</b> <br>
There are no values assosiated with the value...so would a <i>set</i> be better?</p>
| 79
|
2009-02-04T23:28:41Z
| 578,968
|
<p><a href="http://docs.python.org/library/sets.html"><code>set()</code></a> is exactly what you want. O(1) lookups, and smaller than a dict.</p>
| 17
|
2009-02-23T19:24:39Z
|
[
"python",
"performance"
] |
Python: List vs Dict for look up table
| 513,882
|
<p>I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a <i>list</i> or <i>dict</i>?</p>
<p>I know you can do something like this for both:</p>
<pre><code>if something in dict_of_stuff:
pass
</code></pre>
<p>and</p>
<pre><code>if something in list_of_stuff:
pass
</code></pre>
<p>My thought is the dict will be faster and more efficient.</p>
<p>Thanks for your help.</p>
<p><b>EDIT 1</b> <br>
Little more info on what I'm trying to do. <a href="http://projecteuler.net/index.php?section=problems&id=92">Euler Problem 92</a>. I'm making a look up table to see if a value calculated has all ready been calculated. </p>
<p><b>EDIT 2</b> <br>
Efficiency for look up.</p>
<p><b>EDIT 3</b> <br>
There are no values assosiated with the value...so would a <i>set</i> be better?</p>
| 79
|
2009-02-04T23:28:41Z
| 11,241,481
|
<p>I did some benchmarking and it turns out that dict is faster than both list and set for large data sets, running python 2.7.3 on an i7 CPU on linux:</p>
<ul>
<li><p><code>python -mtimeit -s 'd=range(10**7)' '5*10**6 in d'</code></p>
<p>10 loops, best of 3: 64.2 msec per loop</p></li>
<li><p><code>python -mtimeit -s 'd=dict.fromkeys(range(10**7))' '5*10**6 in d'</code></p>
<p>10000000 loops, best of 3: 0.0759 usec per loop</p></li>
<li><p><code>python -mtimeit -s 'from sets import Set; d=Set(range(10**7))' '5*10**6 in d'</code></p>
<p>1000000 loops, best of 3: 0.262 usec per loop</p></li>
</ul>
<p>As you can see, dict is considerably faster than list and about 3 times faster than set. In some applications you might still want to choose set for the beauty of it, though. And if the data sets are really small (< 1000 elements) lists perform pretty well. </p>
| 12
|
2012-06-28T09:16:06Z
|
[
"python",
"performance"
] |
How to split a string by using [] in Python
| 514,029
|
<p>So from this string:</p>
<p>"name[id]"</p>
<p>I need this:</p>
<p>"id"</p>
<p>I used str.split ('[]'), but it didn't work. Does it only take a single delimiter?</p>
| 2
|
2009-02-05T00:37:27Z
| 514,045
|
<p>Use a regular expression:</p>
<pre><code>import re
s = "name[id]"
re.find(r"\[(.*?)\]", s).group(1) # = 'id'
</code></pre>
<p><code>str.split()</code> takes a string on which to split input. For instance:</p>
<pre><code>"i,split,on commas".split(',') # = ['i', 'split', 'on commas']
</code></pre>
<p>The <code>re</code> module also allows you to split by regular expression, which can be <em>very</em> useful, and I think is what you meant to do.</p>
<pre><code>import re
s = "name[id]"
# split by either a '[' or a ']'
re.split('\[|\]', s) # = ['name', 'id', '']
</code></pre>
| 13
|
2009-02-05T00:42:05Z
|
[
"python",
"string"
] |
How to split a string by using [] in Python
| 514,029
|
<p>So from this string:</p>
<p>"name[id]"</p>
<p>I need this:</p>
<p>"id"</p>
<p>I used str.split ('[]'), but it didn't work. Does it only take a single delimiter?</p>
| 2
|
2009-02-05T00:37:27Z
| 514,047
|
<p>Either</p>
<pre><code>"name[id]".split('[')[1][:-1] == "id"
</code></pre>
<p>or</p>
<pre><code>"name[id]".split('[')[1].split(']')[0] == "id"
</code></pre>
<p>or</p>
<pre><code>re.search(r'\[(.*?)\]',"name[id]").group(1) == "id"
</code></pre>
<p>or</p>
<pre><code>re.split(r'[\[\]]',"name[id]")[1] == "id"
</code></pre>
| 7
|
2009-02-05T00:42:15Z
|
[
"python",
"string"
] |
How to split a string by using [] in Python
| 514,029
|
<p>So from this string:</p>
<p>"name[id]"</p>
<p>I need this:</p>
<p>"id"</p>
<p>I used str.split ('[]'), but it didn't work. Does it only take a single delimiter?</p>
| 2
|
2009-02-05T00:37:27Z
| 514,049
|
<p>str.split uses the entire parameter to split a string. Try:</p>
<pre><code>str.split("[")[1].split("]")[0]
</code></pre>
| -1
|
2009-02-05T00:43:14Z
|
[
"python",
"string"
] |
How to split a string by using [] in Python
| 514,029
|
<p>So from this string:</p>
<p>"name[id]"</p>
<p>I need this:</p>
<p>"id"</p>
<p>I used str.split ('[]'), but it didn't work. Does it only take a single delimiter?</p>
| 2
|
2009-02-05T00:37:27Z
| 514,054
|
<p>Yes, the delimiter is the whole string argument passed to split. So your example would only split a string like 'name[]id[]'.</p>
<p>Try eg. something like:</p>
<pre><code>'name[id]'.split('[', 1)[-1].split(']', 1)[0]
'name[id]'.split('[', 1)[-1].rstrip(']')
</code></pre>
| 3
|
2009-02-05T00:43:43Z
|
[
"python",
"string"
] |
How to split a string by using [] in Python
| 514,029
|
<p>So from this string:</p>
<p>"name[id]"</p>
<p>I need this:</p>
<p>"id"</p>
<p>I used str.split ('[]'), but it didn't work. Does it only take a single delimiter?</p>
| 2
|
2009-02-05T00:37:27Z
| 514,096
|
<p>I'm not a fan of regex, but in cases like it often provides the best solution.</p>
<p>Triptych already recommended this, but I'd like to point out that the ?P<> group assignment can be used to assign a match to a dictionary key:</p>
<pre><code>>>> m = re.match(r'.*\[(?P<id>\w+)\]', 'name[id]')
>>> result_dict = m.groupdict()
>>> result_dict
{'id': 'id'}
>>>
</code></pre>
| 2
|
2009-02-05T00:58:34Z
|
[
"python",
"string"
] |
How to split a string by using [] in Python
| 514,029
|
<p>So from this string:</p>
<p>"name[id]"</p>
<p>I need this:</p>
<p>"id"</p>
<p>I used str.split ('[]'), but it didn't work. Does it only take a single delimiter?</p>
| 2
|
2009-02-05T00:37:27Z
| 514,141
|
<p>You don't actually need regular expressions for this. The .index() function and string slicing will work fine.</p>
<p>Say we have:</p>
<pre><code>>>> s = 'name[id]'
</code></pre>
<p>Then:</p>
<pre><code>>>> s[s.index('[')+1:s.index(']')]
'id'
</code></pre>
<p>To me, this is easy to read: "start one character after the [ and finish before the ]".</p>
| 1
|
2009-02-05T01:10:52Z
|
[
"python",
"string"
] |
How to split a string by using [] in Python
| 514,029
|
<p>So from this string:</p>
<p>"name[id]"</p>
<p>I need this:</p>
<p>"id"</p>
<p>I used str.split ('[]'), but it didn't work. Does it only take a single delimiter?</p>
| 2
|
2009-02-05T00:37:27Z
| 514,318
|
<pre><code>def between_brackets(text):
return text.partition('[')[2].partition(']')[0]
</code></pre>
<p>This will also work even if your string does not contain a <code>[â¦]</code> construct, and it assumes an implied <code>]</code> at the end in the case you have only a <code>[</code> somewhere in the string.</p>
| 1
|
2009-02-05T02:37:45Z
|
[
"python",
"string"
] |
How to split a string by using [] in Python
| 514,029
|
<p>So from this string:</p>
<p>"name[id]"</p>
<p>I need this:</p>
<p>"id"</p>
<p>I used str.split ('[]'), but it didn't work. Does it only take a single delimiter?</p>
| 2
|
2009-02-05T00:37:27Z
| 2,739,117
|
<p>I'm new to python and this is an old question, but maybe this?</p>
<p><code>str.split('[')[1].strip(']')</code></p>
| 0
|
2010-04-29T16:40:45Z
|
[
"python",
"string"
] |
Elegant ways to return multiple values from a function
| 514,038
|
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p>
<p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the parameters by reference or pointer instead of returning them. </p>
<p>Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass. </p>
<p>The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity. </p>
<p>Furthermore, a lot of times there's one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types.</p>
<p>The one language I'm aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking:</p>
<pre><code>a, b = foo(c) # a and b are regular variables.
myTuple = foo(c) # myTuple is a tuple of (a, b)
</code></pre>
<p>Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you've seen in non-mainstream languages are welcome.</p>
| 27
|
2009-02-05T00:39:48Z
| 514,053
|
<p>i thinks python's is the most natural way, when I had to do same thing in php the only was to wrap return into an array. it does have similar unpacking though.</p>
| 3
|
2009-02-05T00:43:33Z
|
[
"python",
"function",
"language-agnostic",
"language-design",
"syntactic-sugar"
] |
Elegant ways to return multiple values from a function
| 514,038
|
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p>
<p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the parameters by reference or pointer instead of returning them. </p>
<p>Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass. </p>
<p>The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity. </p>
<p>Furthermore, a lot of times there's one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types.</p>
<p>The one language I'm aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking:</p>
<pre><code>a, b = foo(c) # a and b are regular variables.
myTuple = foo(c) # myTuple is a tuple of (a, b)
</code></pre>
<p>Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you've seen in non-mainstream languages are welcome.</p>
| 27
|
2009-02-05T00:39:48Z
| 514,069
|
<p>Often in php I'll use a referenced input:</p>
<pre><code>public function Validates(&$errors=array()) {
if($failstest) {
$errors[] = "It failed";
return false;
} else {
return true;
}
}
</code></pre>
<p>That gives me the error messages I want without polluting the bool return, so I can still do:</p>
<pre><code>if($this->Validates()) ...
</code></pre>
| 1
|
2009-02-05T00:48:04Z
|
[
"python",
"function",
"language-agnostic",
"language-design",
"syntactic-sugar"
] |
Elegant ways to return multiple values from a function
| 514,038
|
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p>
<p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the parameters by reference or pointer instead of returning them. </p>
<p>Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass. </p>
<p>The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity. </p>
<p>Furthermore, a lot of times there's one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types.</p>
<p>The one language I'm aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking:</p>
<pre><code>a, b = foo(c) # a and b are regular variables.
myTuple = foo(c) # myTuple is a tuple of (a, b)
</code></pre>
<p>Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you've seen in non-mainstream languages are welcome.</p>
| 27
|
2009-02-05T00:39:48Z
| 514,071
|
<p>Pretty much all ML-influenced functional langues (which is most of them) also have great tuple support that makes this sort of thing trivial.</p>
<p>For C++ I like boost::tuple plus boost::tie (or std::tr1 if you have it)</p>
<pre><code>typedef boost::tuple<double,double,double> XYZ;
XYZ foo();
double x,y,z;
boost::tie(x,y,z) = foo();
</code></pre>
<p>or a less contrived example</p>
<pre><code>MyMultimap::iterator lower,upper;
boost::tie(lower,upper) = some_map.equal_range(key);
</code></pre>
| 24
|
2009-02-05T00:48:27Z
|
[
"python",
"function",
"language-agnostic",
"language-design",
"syntactic-sugar"
] |
Elegant ways to return multiple values from a function
| 514,038
|
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p>
<p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the parameters by reference or pointer instead of returning them. </p>
<p>Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass. </p>
<p>The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity. </p>
<p>Furthermore, a lot of times there's one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types.</p>
<p>The one language I'm aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking:</p>
<pre><code>a, b = foo(c) # a and b are regular variables.
myTuple = foo(c) # myTuple is a tuple of (a, b)
</code></pre>
<p>Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you've seen in non-mainstream languages are welcome.</p>
| 27
|
2009-02-05T00:39:48Z
| 514,093
|
<p>If a function returns multiple values, that is a sign you might be witnessing the <a href="http://www.martinfowler.com/bliki/DataClump.html" rel="nofollow">"Data Clump" code smell</a>. Often data clumps are primitive values that nobody thinks to turn into an object, but interesting stuff happens as you begin to look for behavior to move into the new objects.</p>
<p>Writing tiny helper classes might be extra typing, but it provides clear names and strong type checking. Developers maintaining your code will appreciate it. And useful small classes often grow up to be used in other code.</p>
<p>Also, if a function returns multiple values, then it might be doing too much work. Could the function be refactored into two (or more) small functions?</p>
| 5
|
2009-02-05T00:57:53Z
|
[
"python",
"function",
"language-agnostic",
"language-design",
"syntactic-sugar"
] |
Elegant ways to return multiple values from a function
| 514,038
|
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p>
<p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the parameters by reference or pointer instead of returning them. </p>
<p>Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass. </p>
<p>The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity. </p>
<p>Furthermore, a lot of times there's one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types.</p>
<p>The one language I'm aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking:</p>
<pre><code>a, b = foo(c) # a and b are regular variables.
myTuple = foo(c) # myTuple is a tuple of (a, b)
</code></pre>
<p>Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you've seen in non-mainstream languages are welcome.</p>
| 27
|
2009-02-05T00:39:48Z
| 514,114
|
<p>A few languages, notably Lisp and JavaScript, have a feature called destructuring assignment or destructuring bind. This is essentially tuple unpacking on steroids: rather than being limited to sequences like tuples, lists, or generators, you can unpack more complex object structures in an assignment statement. For more details, see <a href="http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/mac_destructuring-bind.html">here for the Lisp version</a> or <a href="https://developer.mozilla.org/en/New_in_JavaScript_1.7#Destructuring_assignment">here for the (rather more readable) JavaScript version</a>.</p>
<p>Other than that, I don't know of many language features for dealing with multiple return values generally. However, there are a few specific uses of multiple return values that can often be replaced by other language features. For example, if one of the values is an error code, it might be better replaced with an exception.</p>
<p>While creating new classes to hold multiple return values feels like clutter, the fact that you're returning those values together is often a sign that your code will be better overall once the class is created. In particular, other functions that deal with the same data can then move to the new class, which may make your code easier to follow. This isn't universally true, but it's worth considering. (Cpeterso's answer about data clumps expresses this in more detail).</p>
| 9
|
2009-02-05T01:05:05Z
|
[
"python",
"function",
"language-agnostic",
"language-design",
"syntactic-sugar"
] |
Elegant ways to return multiple values from a function
| 514,038
|
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p>
<p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the parameters by reference or pointer instead of returning them. </p>
<p>Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass. </p>
<p>The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity. </p>
<p>Furthermore, a lot of times there's one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types.</p>
<p>The one language I'm aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking:</p>
<pre><code>a, b = foo(c) # a and b are regular variables.
myTuple = foo(c) # myTuple is a tuple of (a, b)
</code></pre>
<p>Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you've seen in non-mainstream languages are welcome.</p>
| 27
|
2009-02-05T00:39:48Z
| 514,133
|
<p>Nobody seems to have mentioned Perl yet.</p>
<pre><code>sub myfunc {
return 1, 2;
}
my($val1, $val2) = myfunc();
</code></pre>
| 4
|
2009-02-05T01:09:13Z
|
[
"python",
"function",
"language-agnostic",
"language-design",
"syntactic-sugar"
] |
Elegant ways to return multiple values from a function
| 514,038
|
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p>
<p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the parameters by reference or pointer instead of returning them. </p>
<p>Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass. </p>
<p>The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity. </p>
<p>Furthermore, a lot of times there's one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types.</p>
<p>The one language I'm aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking:</p>
<pre><code>a, b = foo(c) # a and b are regular variables.
myTuple = foo(c) # myTuple is a tuple of (a, b)
</code></pre>
<p>Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you've seen in non-mainstream languages are welcome.</p>
| 27
|
2009-02-05T00:39:48Z
| 514,300
|
<p>PHP example:</p>
<pre><code>function my_funct() {
$x = "hello";
$y = "world";
return array($x, $y);
}
</code></pre>
<p>Then, when run:</p>
<pre><code>list($x, $y) = my_funct();
echo $x.' '.$y; // "hello world"
</code></pre>
| 7
|
2009-02-05T02:31:32Z
|
[
"python",
"function",
"language-agnostic",
"language-design",
"syntactic-sugar"
] |
Elegant ways to return multiple values from a function
| 514,038
|
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p>
<p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the parameters by reference or pointer instead of returning them. </p>
<p>Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass. </p>
<p>The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity. </p>
<p>Furthermore, a lot of times there's one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types.</p>
<p>The one language I'm aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking:</p>
<pre><code>a, b = foo(c) # a and b are regular variables.
myTuple = foo(c) # myTuple is a tuple of (a, b)
</code></pre>
<p>Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you've seen in non-mainstream languages are welcome.</p>
| 27
|
2009-02-05T00:39:48Z
| 514,433
|
<p>In <code>C++</code> you can pass a container into the function so the function can fill it:</p>
<pre><code>void getValues(std::vector<int>* result){
result->push_back(2);
result->push_back(6);
result->push_back(73);
}
</code></pre>
<p>You could also have the function return a smart pointer (use <code>shared_ptr</code>) to a <code>vector</code>:</p>
<pre><code>boost::shared_ptr< std::vector<int> > getValues(){
boost::shared_ptr< std::vector<int> > vec(new std::vector<int>(3));
(*vec)[0] = 2;
(*vec)[1] = 6;
(*vec)[2] = 73;
return vec;
}
</code></pre>
| 0
|
2009-02-05T03:31:56Z
|
[
"python",
"function",
"language-agnostic",
"language-design",
"syntactic-sugar"
] |
Elegant ways to return multiple values from a function
| 514,038
|
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p>
<p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the parameters by reference or pointer instead of returning them. </p>
<p>Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass. </p>
<p>The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity. </p>
<p>Furthermore, a lot of times there's one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types.</p>
<p>The one language I'm aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking:</p>
<pre><code>a, b = foo(c) # a and b are regular variables.
myTuple = foo(c) # myTuple is a tuple of (a, b)
</code></pre>
<p>Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you've seen in non-mainstream languages are welcome.</p>
| 27
|
2009-02-05T00:39:48Z
| 514,509
|
<p>Even if you ignore the wonderful newer destructuring assignment <a href="http://stackoverflow.com/questions/514038/elegant-ways-to-return-multiple-values-from-a-function/514114#514114">Moss Collum mentioned</a>, JavaScript is pretty nice on returning multiple results.</p>
<pre><code>function give7and5() {
return {x:7,y:5};
}
a=give7and5();
console.log(a.x,a.y);
7 5
</code></pre>
| 2
|
2009-02-05T04:02:06Z
|
[
"python",
"function",
"language-agnostic",
"language-design",
"syntactic-sugar"
] |
Elegant ways to return multiple values from a function
| 514,038
|
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p>
<p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the parameters by reference or pointer instead of returning them. </p>
<p>Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass. </p>
<p>The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity. </p>
<p>Furthermore, a lot of times there's one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types.</p>
<p>The one language I'm aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking:</p>
<pre><code>a, b = foo(c) # a and b are regular variables.
myTuple = foo(c) # myTuple is a tuple of (a, b)
</code></pre>
<p>Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you've seen in non-mainstream languages are welcome.</p>
| 27
|
2009-02-05T00:39:48Z
| 514,556
|
<p>As for Java, see Bruce Eckel's <a href="http://rads.stackoverflow.com/amzn/click/0131872486" rel="nofollow"><em>Thinking in Java</em></a> for a nice solution (pp. 621 ff).</p>
<p>In essence, you can define a class equivalent to the following:</p>
<pre><code>public class Pair<T,U> {
public final T left;
public final U right;
public Pair (T t, U u) { left = t; right = u; }
}
</code></pre>
<p>You can then use this as the return type for a function, with appropriate type parameters:</p>
<pre><code>public Pair<String,Integer> getAnswer() {
return new Pair<String,Integer>("the universe", 42);
}
</code></pre>
<p>After invoking that function:</p>
<pre><code>Pair<String,Integer> myPair = getAnswer();
</code></pre>
<p>you can refer to <code>myPair.left</code> and <code>myPair.right</code> for access to the constituent values.</p>
<p>There are other syntactical sugar options, but the above is the key point.</p>
| 4
|
2009-02-05T04:17:55Z
|
[
"python",
"function",
"language-agnostic",
"language-design",
"syntactic-sugar"
] |
Elegant ways to return multiple values from a function
| 514,038
|
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p>
<p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the parameters by reference or pointer instead of returning them. </p>
<p>Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass. </p>
<p>The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity. </p>
<p>Furthermore, a lot of times there's one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types.</p>
<p>The one language I'm aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking:</p>
<pre><code>a, b = foo(c) # a and b are regular variables.
myTuple = foo(c) # myTuple is a tuple of (a, b)
</code></pre>
<p>Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you've seen in non-mainstream languages are welcome.</p>
| 27
|
2009-02-05T00:39:48Z
| 514,679
|
<p>Both <a href="http://www.lua.org/" rel="nofollow">Lua</a> and CLU (by Barbara Liskov's group at MIT) have multiple return values for all functions---it is always the default. I believe the designers of Lua were inspired by CLU. I like having multiple values be the default for calls and returns; I think it is a very elegant way of thinking about things. In Lua and CLU this mechanism is completely independent of tuples and/or records.</p>
<p>The portable assembly language <a href="http://www.cminusminus.org/" rel="nofollow">C--</a> supports multiple return values for its native calling convention but not for the C calling convention. There the idea is to enable a compiler writer to return multiple values in individual hardware registers rather than having to put the values in a clump in memory and return a pointer to that clump (or as in C, have the caller pass a pointer to an empty clump).</p>
<p>Like any mechanism, multiple return values can be abused, but I don't think it is any more unreasonable to have a function return multiple values than it is to have a struct contain multiple values.</p>
| 1
|
2009-02-05T05:16:39Z
|
[
"python",
"function",
"language-agnostic",
"language-design",
"syntactic-sugar"
] |
Elegant ways to return multiple values from a function
| 514,038
|
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p>
<p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the parameters by reference or pointer instead of returning them. </p>
<p>Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass. </p>
<p>The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity. </p>
<p>Furthermore, a lot of times there's one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types.</p>
<p>The one language I'm aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking:</p>
<pre><code>a, b = foo(c) # a and b are regular variables.
myTuple = foo(c) # myTuple is a tuple of (a, b)
</code></pre>
<p>Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you've seen in non-mainstream languages are welcome.</p>
| 27
|
2009-02-05T00:39:48Z
| 3,163,927
|
<p>c#</p>
<pre><code>public struct tStruct
{
int x;
int y;
string text;
public tStruct(int nx, int ny, string stext)
{
this.x = nx;
this.y = ny;
this.text = stext;
}
}
public tStruct YourFunction()
{
return new tStruct(50, 100, "hello world");
}
public void YourPrintFunction(string sMessage)
{
Console.WriteLine(sMessage);
}
</code></pre>
<p>in Lua you call</p>
<pre><code>MyVar = YourFunction();
YourPrintfFunction(MyVar.x);
YourPrintfFunction(MyVar.y);
YourPrintfFunction(MyVar.text);
</code></pre>
<p>Output:
50
100
hello world</p>
<p>Paul</p>
| 0
|
2010-07-02T07:23:29Z
|
[
"python",
"function",
"language-agnostic",
"language-design",
"syntactic-sugar"
] |
Elegant ways to return multiple values from a function
| 514,038
|
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p>
<p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the parameters by reference or pointer instead of returning them. </p>
<p>Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass. </p>
<p>The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity. </p>
<p>Furthermore, a lot of times there's one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types.</p>
<p>The one language I'm aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking:</p>
<pre><code>a, b = foo(c) # a and b are regular variables.
myTuple = foo(c) # myTuple is a tuple of (a, b)
</code></pre>
<p>Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you've seen in non-mainstream languages are welcome.</p>
| 27
|
2009-02-05T00:39:48Z
| 4,869,624
|
<p>By the way, Scala can return multiple values as follows (pasted from an interpreter session):</p>
<pre><code>scala> def return2 = (1,2)
return2: (Int, Int)
scala> val (a1,a2) = return2
a1: Int = 1
a2: Int = 2
</code></pre>
<p>This is a special case of using <a href="http://www.nearinfinity.com/blogs/bryan_weber/scala_pattern_matching.html" rel="nofollow">pattern matching for assignment</a>.</p>
| 0
|
2011-02-02T00:39:36Z
|
[
"python",
"function",
"language-agnostic",
"language-design",
"syntactic-sugar"
] |
Elegant ways to return multiple values from a function
| 514,038
|
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p>
<p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the parameters by reference or pointer instead of returning them. </p>
<p>Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass. </p>
<p>The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity. </p>
<p>Furthermore, a lot of times there's one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types.</p>
<p>The one language I'm aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking:</p>
<pre><code>a, b = foo(c) # a and b are regular variables.
myTuple = foo(c) # myTuple is a tuple of (a, b)
</code></pre>
<p>Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you've seen in non-mainstream languages are welcome.</p>
| 27
|
2009-02-05T00:39:48Z
| 10,018,424
|
<p>Here was my Ruby idea to return a special value that looks and acts like a scalar but actually has hidden attributes on it:</p>
<p><a href="https://gist.github.com/2305169" rel="nofollow">https://gist.github.com/2305169</a></p>
| 0
|
2012-04-04T20:03:10Z
|
[
"python",
"function",
"language-agnostic",
"language-design",
"syntactic-sugar"
] |
Extension methods in Python
| 514,068
|
<p>Does Python have extension methods like C#? Is it possible to call a method like:</p>
<pre><code>MyRandomMethod()
</code></pre>
<p>on existing types like <code>int</code>?</p>
<pre><code>myInt.MyRandomMethod()
</code></pre>
| 23
|
2009-02-05T00:47:37Z
| 514,081
|
<p>not sure if that what you're asking but you can extend existing types and then call whatever you like on the new thing:</p>
<pre><code>class int(int):
def random_method(self):
return 4 # guaranteed to be random
v = int(5) # you'll have to instantiate all you variables like this
v.random_method()
class int(int):
def xkcd(self):
import antigravity
print(42)
>>>v.xkcd()
Traceback (most recent call last):
File "<pyshell#81>", line 1, in <module>
v.xkcd()
AttributeError: 'int' object has no attribute 'xkcd'
c = int(1)
>>> c.random_method()
4
>>> c.xkcd()
42
</code></pre>
<p>hope that clarifies your question</p>
| 7
|
2009-02-05T00:53:57Z
|
[
"python",
"function",
"extension-methods"
] |
Extension methods in Python
| 514,068
|
<p>Does Python have extension methods like C#? Is it possible to call a method like:</p>
<pre><code>MyRandomMethod()
</code></pre>
<p>on existing types like <code>int</code>?</p>
<pre><code>myInt.MyRandomMethod()
</code></pre>
| 23
|
2009-02-05T00:47:37Z
| 514,101
|
<p>You can add whatever methods you like on class objects defined in Python code (AKA monkey patching):</p>
<pre><code>>>> class A(object):
>>> pass
>>> def stuff(self):
>>> print self
>>> A.test = stuff
>>> A().test()
</code></pre>
<p>This does not work on builtin types, because their <code>__dict__</code> is not writable (it's a <code>dictproxy</code>).</p>
<p>So no, there is no "real" extension method mechanism in Python.</p>
| 32
|
2009-02-05T00:59:31Z
|
[
"python",
"function",
"extension-methods"
] |
Extension methods in Python
| 514,068
|
<p>Does Python have extension methods like C#? Is it possible to call a method like:</p>
<pre><code>MyRandomMethod()
</code></pre>
<p>on existing types like <code>int</code>?</p>
<pre><code>myInt.MyRandomMethod()
</code></pre>
| 23
|
2009-02-05T00:47:37Z
| 514,148
|
<p>Another option is to override the meta-class. This allows you to, among other things, specify functions that should exist in all classes.</p>
<p>This article starts to discuss it:</p>
<p><a href="http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html" rel="nofollow">http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html</a></p>
| 0
|
2009-02-05T01:14:45Z
|
[
"python",
"function",
"extension-methods"
] |
Extension methods in Python
| 514,068
|
<p>Does Python have extension methods like C#? Is it possible to call a method like:</p>
<pre><code>MyRandomMethod()
</code></pre>
<p>on existing types like <code>int</code>?</p>
<pre><code>myInt.MyRandomMethod()
</code></pre>
| 23
|
2009-02-05T00:47:37Z
| 517,056
|
<p>I've had great luck with the method described here:</p>
<p><a href="http://mail.python.org/pipermail/python-dev/2008-January/076194.html" rel="nofollow">http://mail.python.org/pipermail/python-dev/2008-January/076194.html</a></p>
<p>I have no idea if it works on builtins though.</p>
| 1
|
2009-02-05T17:59:17Z
|
[
"python",
"function",
"extension-methods"
] |
What's the bad magic number error?
| 514,371
|
<p>What's the "Bad magic number" ImportError in python, and how do I fix it?</p>
<p>The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm not sure why.</p>
<p>The information python's providing in the traceback isn't particularly helpful (which is why I was asking here...), but here it is in case it helps:</p>
<pre><code>Traceback (most recent call last):
File "run.py", line 7, in <module>
from Normalization import Normalizer
</code></pre>
| 140
|
2009-02-05T02:59:47Z
| 514,395
|
<p>The magic number comes from UNIX-type systems where the first few bytes of a file held a marker indicating the file type.</p>
<p>Python puts a similar marker into its <code>pyc</code> files when it creates them.</p>
<p>Then the python interpreter makes sure this number is correct when loading it.</p>
<p>Anything that damages this magic number will cause your problem. This includes editing the <code>pyc</code> file or trying to run a <code>pyc</code> from a different version of python (usually later) than your interpreter.</p>
<p>If they are <em>your</em> <code>pyc</code> files, just delete them and let the interpreter re-compile the <code>py</code> files. On UNIX type systems, that could be something as simple as:</p>
<pre><code>rm *.pyc
</code></pre>
<p>or:</p>
<pre><code>find . -name '*.pyc' -delete
</code></pre>
<p>If they are not yours, you'll have to either get the <code>py</code> files for re-compilation, or an interpreter that can run the <code>pyc</code> files with that particular magic value.</p>
<p>One thing that might be causing the intermittent nature. The <code>pyc</code> that's causing the problem may only be imported under certain conditions. It's highly unlikely it would import sometimes. You should check the actual full stack trace when the import fails?</p>
<p>As an aside, the first word of all my <code>2.5.1(r251:54863)</code> <code>pyc</code> files is <code>62131</code>, <code>2.6.1(r261:67517)</code> is <code>62161</code>. The list of all magic numbers can be found in <code>Python/import.c</code>, reproduced here for completeness (current as at the time the answer was posted, it may have changed since then):</p>
<pre><code>1.5: 20121
1.5.1: 20121
1.5.2: 20121
1.6: 50428
2.0: 50823
2.0.1: 50823
2.1: 60202
2.1.1: 60202
2.1.2: 60202
2.2: 60717
2.3a0: 62011
2.3a0: 62021
2.3a0: 62011
2.4a0: 62041
2.4a3: 62051
2.4b1: 62061
2.5a0: 62071
2.5a0: 62081
2.5a0: 62091
2.5a0: 62092
2.5b3: 62101
2.5b3: 62111
2.5c1: 62121
2.5c2: 62131
2.6a0: 62151
2.6a1: 62161
2.7a0: 62171
</code></pre>
| 174
|
2009-02-05T03:09:40Z
|
[
"python"
] |
What's the bad magic number error?
| 514,371
|
<p>What's the "Bad magic number" ImportError in python, and how do I fix it?</p>
<p>The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm not sure why.</p>
<p>The information python's providing in the traceback isn't particularly helpful (which is why I was asking here...), but here it is in case it helps:</p>
<pre><code>Traceback (most recent call last):
File "run.py", line 7, in <module>
from Normalization import Normalizer
</code></pre>
| 140
|
2009-02-05T02:59:47Z
| 2,905,435
|
<p>Deleting all .pyc files will fix "Bad Magic Number" error.</p>
<pre><code>find . -name "*.pyc" -delete
</code></pre>
| 28
|
2010-05-25T14:12:02Z
|
[
"python"
] |
What's the bad magic number error?
| 514,371
|
<p>What's the "Bad magic number" ImportError in python, and how do I fix it?</p>
<p>The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm not sure why.</p>
<p>The information python's providing in the traceback isn't particularly helpful (which is why I was asking here...), but here it is in case it helps:</p>
<pre><code>Traceback (most recent call last):
File "run.py", line 7, in <module>
from Normalization import Normalizer
</code></pre>
| 140
|
2009-02-05T02:59:47Z
| 2,905,486
|
<p>This is much more efficent than above.</p>
<pre><code>find {directory-of-.pyc-files} -name "*.pyc" -print0 | xargs -0 rm -rf
</code></pre>
<p>where <code>{directory-of-.pyc-files}</code> is the directory that contains the compiled python files. </p>
| 0
|
2010-05-25T14:18:09Z
|
[
"python"
] |
What's the bad magic number error?
| 514,371
|
<p>What's the "Bad magic number" ImportError in python, and how do I fix it?</p>
<p>The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm not sure why.</p>
<p>The information python's providing in the traceback isn't particularly helpful (which is why I was asking here...), but here it is in case it helps:</p>
<pre><code>Traceback (most recent call last):
File "run.py", line 7, in <module>
from Normalization import Normalizer
</code></pre>
| 140
|
2009-02-05T02:59:47Z
| 4,854,784
|
<p>Loading a python3 generated *.pyc file with python2 also causes this error</p>
| 10
|
2011-01-31T18:52:09Z
|
[
"python"
] |
What's the bad magic number error?
| 514,371
|
<p>What's the "Bad magic number" ImportError in python, and how do I fix it?</p>
<p>The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm not sure why.</p>
<p>The information python's providing in the traceback isn't particularly helpful (which is why I was asking here...), but here it is in case it helps:</p>
<pre><code>Traceback (most recent call last):
File "run.py", line 7, in <module>
from Normalization import Normalizer
</code></pre>
| 140
|
2009-02-05T02:59:47Z
| 16,791,304
|
<p>Take the pyc file to a windows machine. Use any Hex editor to open this pyc file. I used freeware 'HexEdit'. Now read hex value of first two bytes. In my case, these were 03 f3.</p>
<p>Open calc and convert its display mode to Programmer (Scientific in XP) to see Hex and Decimal conversion. Select "Hex" from Radio button. Enter values as second byte first and then the first byte i.e f303 Now click on "Dec" (Decimal) radio button. The value displayed is one which is correspond to the magic number aka version of python. </p>
<p>So, considering the table provided in earlier reply</p>
<ul>
<li>1.5 => 20121 => 4E99 so files would have first byte as 99 and second as 4e</li>
<li>1.6 => 50428 => C4FC so files would have first byte as fc and second as c4</li>
</ul>
| 5
|
2013-05-28T11:49:00Z
|
[
"python"
] |
What's the bad magic number error?
| 514,371
|
<p>What's the "Bad magic number" ImportError in python, and how do I fix it?</p>
<p>The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm not sure why.</p>
<p>The information python's providing in the traceback isn't particularly helpful (which is why I was asking here...), but here it is in case it helps:</p>
<pre><code>Traceback (most recent call last):
File "run.py", line 7, in <module>
from Normalization import Normalizer
</code></pre>
| 140
|
2009-02-05T02:59:47Z
| 24,394,381
|
<p>I had a strange case of Bad Magic Number error using a very old (1.5.2) implementation. I generated a .pyo file and that triggered the error. Bizarrely, the problem was solved by changing the name of the module. The offending name was sms.py. If I generated an sms.pyo from that module, Bad Magic Number error was the result. When I changed the name to smst.py, the error went away. I checked back and forth to see if sms.py somehow interfered with any other module with the same name but I could not find any name collision. Even though the source of this problem remained a mistery for me, I recommend trying a module name change.</p>
| 1
|
2014-06-24T19:06:29Z
|
[
"python"
] |
What's the bad magic number error?
| 514,371
|
<p>What's the "Bad magic number" ImportError in python, and how do I fix it?</p>
<p>The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm not sure why.</p>
<p>The information python's providing in the traceback isn't particularly helpful (which is why I was asking here...), but here it is in case it helps:</p>
<pre><code>Traceback (most recent call last):
File "run.py", line 7, in <module>
from Normalization import Normalizer
</code></pre>
| 140
|
2009-02-05T02:59:47Z
| 34,078,936
|
<p>In my case it was not <code>.pyc</code> but old binary <code>.mo</code> translation files after I renamed my own module, so inside this module folder I had to run</p>
<pre><code>find . -name \*.po -execdir sh -c 'msgfmt "$0" -o `basename $0 .po`.mo' '{}' \;
</code></pre>
<p>(please do backup and try to fix <code>.pyc</code> files first)</p>
| 0
|
2015-12-04T00:35:50Z
|
[
"python"
] |
What's the bad magic number error?
| 514,371
|
<p>What's the "Bad magic number" ImportError in python, and how do I fix it?</p>
<p>The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm not sure why.</p>
<p>The information python's providing in the traceback isn't particularly helpful (which is why I was asking here...), but here it is in case it helps:</p>
<pre><code>Traceback (most recent call last):
File "run.py", line 7, in <module>
from Normalization import Normalizer
</code></pre>
| 140
|
2009-02-05T02:59:47Z
| 39,410,760
|
<p>Don't delete them!!! Until..........</p>
<p>Find a version on your git, svn or copy folder that works. </p>
<p>Delete them and then recover all .pyc. </p>
<p>That's work for me. </p>
| 0
|
2016-09-09T11:39:53Z
|
[
"python"
] |
Python: loop over consecutive characters?
| 514,448
|
<p>In Python (specifically Python 3.0 but I don't think it matters), how do I easily write a loop over a sequence of characters having consecutive character codes? I want to do something like this pseudocode:</p>
<pre><code>for Ch from 'a' to 'z' inclusive: #
f(Ch)
</code></pre>
<p>Example: how about a nice "pythonic" version of the following?</p>
<pre><code>def Pangram(Str):
''' Returns True if Str contains the whole alphabet, else False '''
for Ch from 'a' to 'z' inclusive: #
M[Ch] = False
for J in range(len(Str)):
Ch = lower(Str[J])
if 'a' <= Ch <= 'z':
M[Ch] = True
return reduce(and, M['a'] to M['z'] inclusive) #
</code></pre>
<p>The lines marked # are pseudocode. Of course reduce() is real Python! </p>
<p>Dear wizards (specially old, gray-bearded wizards), perhaps you can tell that my favorite language used to be Pascal.</p>
| 8
|
2009-02-05T03:41:31Z
| 514,466
|
<p>You have a constant in the string module called <code>ascii_lowercase</code>, try that out:</p>
<pre><code>>>> from string import ascii_lowercase
</code></pre>
<p>Then you can iterate over the characters in that string.</p>
<pre><code>>>> for i in ascii_lowercase :
... f(i)
</code></pre>
<p>For your pangram question, there is a very simple way to find out if a string contains all the letters of the alphabet. Using ascii_lowercase as before,</p>
<pre><code>>>> def pangram(str) :
... return set(ascii_lowercase).issubset(set(str))
</code></pre>
| 31
|
2009-02-05T03:47:46Z
|
[
"python",
"algorithm",
"python-3.x",
"character"
] |
Python: loop over consecutive characters?
| 514,448
|
<p>In Python (specifically Python 3.0 but I don't think it matters), how do I easily write a loop over a sequence of characters having consecutive character codes? I want to do something like this pseudocode:</p>
<pre><code>for Ch from 'a' to 'z' inclusive: #
f(Ch)
</code></pre>
<p>Example: how about a nice "pythonic" version of the following?</p>
<pre><code>def Pangram(Str):
''' Returns True if Str contains the whole alphabet, else False '''
for Ch from 'a' to 'z' inclusive: #
M[Ch] = False
for J in range(len(Str)):
Ch = lower(Str[J])
if 'a' <= Ch <= 'z':
M[Ch] = True
return reduce(and, M['a'] to M['z'] inclusive) #
</code></pre>
<p>The lines marked # are pseudocode. Of course reduce() is real Python! </p>
<p>Dear wizards (specially old, gray-bearded wizards), perhaps you can tell that my favorite language used to be Pascal.</p>
| 8
|
2009-02-05T03:41:31Z
| 514,517
|
<p>Iterating a constant with all the characters you need is very Pythonic. However if you don't want to import anything and are only working in Unicode, use the built-ins ord() and its inverse chr().</p>
<pre><code>for code in range(ord('a'), ord('z') + 1):
print chr(code)
</code></pre>
| 8
|
2009-02-05T04:04:39Z
|
[
"python",
"algorithm",
"python-3.x",
"character"
] |
Python: loop over consecutive characters?
| 514,448
|
<p>In Python (specifically Python 3.0 but I don't think it matters), how do I easily write a loop over a sequence of characters having consecutive character codes? I want to do something like this pseudocode:</p>
<pre><code>for Ch from 'a' to 'z' inclusive: #
f(Ch)
</code></pre>
<p>Example: how about a nice "pythonic" version of the following?</p>
<pre><code>def Pangram(Str):
''' Returns True if Str contains the whole alphabet, else False '''
for Ch from 'a' to 'z' inclusive: #
M[Ch] = False
for J in range(len(Str)):
Ch = lower(Str[J])
if 'a' <= Ch <= 'z':
M[Ch] = True
return reduce(and, M['a'] to M['z'] inclusive) #
</code></pre>
<p>The lines marked # are pseudocode. Of course reduce() is real Python! </p>
<p>Dear wizards (specially old, gray-bearded wizards), perhaps you can tell that my favorite language used to be Pascal.</p>
| 8
|
2009-02-05T03:41:31Z
| 514,782
|
<p>I would write a function similar to Python's <code>range</code></p>
<pre><code>def alpha_range(*args):
if len(args) == 1:
start, end, step = ord('a'), ord(args[0]), 1
elif len(args) == 2:
start, end, step = ord(args[0]), ord(args[1]), 1
else:
start, end, step = ord(args[0]), ord(args[1]), args[2]
return (chr(i) for i in xrange(start, end, step))
</code></pre>
| 0
|
2009-02-05T06:20:41Z
|
[
"python",
"algorithm",
"python-3.x",
"character"
] |
Python: loop over consecutive characters?
| 514,448
|
<p>In Python (specifically Python 3.0 but I don't think it matters), how do I easily write a loop over a sequence of characters having consecutive character codes? I want to do something like this pseudocode:</p>
<pre><code>for Ch from 'a' to 'z' inclusive: #
f(Ch)
</code></pre>
<p>Example: how about a nice "pythonic" version of the following?</p>
<pre><code>def Pangram(Str):
''' Returns True if Str contains the whole alphabet, else False '''
for Ch from 'a' to 'z' inclusive: #
M[Ch] = False
for J in range(len(Str)):
Ch = lower(Str[J])
if 'a' <= Ch <= 'z':
M[Ch] = True
return reduce(and, M['a'] to M['z'] inclusive) #
</code></pre>
<p>The lines marked # are pseudocode. Of course reduce() is real Python! </p>
<p>Dear wizards (specially old, gray-bearded wizards), perhaps you can tell that my favorite language used to be Pascal.</p>
| 8
|
2009-02-05T03:41:31Z
| 515,427
|
<p>You've got to leave the Pascal-isms behind and learn Python with a fresh perspective.</p>
<pre><code>>>> ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> def pangram( source ):
return all(c in source for c in ascii_lowercase)
>>> pangram('hi mom')
False
>>> pangram(ascii_lowercase)
True
</code></pre>
<p>By limiting yourself to what Pascal offered, you're missing the things Python offers.</p>
<p>And... try to avoid <code>reduce</code>. It often leads to terrible performance problems.</p>
<p><hr /></p>
<p>Edit. Here's another formulation; this one implements set intersection.</p>
<pre><code>>>> def pangram( source ):
>>> notused= [ c for c in ascii_lowercase if c not in source ]
>>> return len(notused) == 0
</code></pre>
<p>This one gives you a piece of diagnostic information for determining what letters are missing from a candidate pangram.</p>
| 6
|
2009-02-05T11:00:09Z
|
[
"python",
"algorithm",
"python-3.x",
"character"
] |
Python: loop over consecutive characters?
| 514,448
|
<p>In Python (specifically Python 3.0 but I don't think it matters), how do I easily write a loop over a sequence of characters having consecutive character codes? I want to do something like this pseudocode:</p>
<pre><code>for Ch from 'a' to 'z' inclusive: #
f(Ch)
</code></pre>
<p>Example: how about a nice "pythonic" version of the following?</p>
<pre><code>def Pangram(Str):
''' Returns True if Str contains the whole alphabet, else False '''
for Ch from 'a' to 'z' inclusive: #
M[Ch] = False
for J in range(len(Str)):
Ch = lower(Str[J])
if 'a' <= Ch <= 'z':
M[Ch] = True
return reduce(and, M['a'] to M['z'] inclusive) #
</code></pre>
<p>The lines marked # are pseudocode. Of course reduce() is real Python! </p>
<p>Dear wizards (specially old, gray-bearded wizards), perhaps you can tell that my favorite language used to be Pascal.</p>
| 8
|
2009-02-05T03:41:31Z
| 7,083,909
|
<p>A more abstract answer would be something like:</p>
<pre><code>>>> x="asdf"
>>> for i in range(len(x)):
... print x[i]
</code></pre>
| 0
|
2011-08-16T19:32:44Z
|
[
"python",
"algorithm",
"python-3.x",
"character"
] |
Help building a regular expression in python using the re module
| 514,475
|
<p>im writing a simple propositional logic formula parser in python which uses regular expressions re module and the lex/yacc module for lexing/parsing. Originally my code could pick out implication as ->, but adding logical equivalence (<->) caused issues with the compiled expressions</p>
<pre><code>IMPLICATION = re.compile('[\s]*\-\>[\s]*')
EQUIVALENCE = re.compile('[\s]*\<\-\>[\s]*')
...
elif self.IMPLICATION.search(formula[0].strip()):
...
elif self.EQUIVALENCE.search(formula[0].strip()):
...
</code></pre>
<p>I originally tried adding [^<] to the front of -> to make it ignore instances of equivalence but this just made it not accept any instances of implication at all. Any possible help would be warmly welcome :)</p>
| 1
|
2009-02-05T03:51:27Z
| 514,502
|
<p>I think you can solve this simply by reordering your checking to match equivalences first, and then implications. However, this seems to work :</p>
<pre><code>>>> IMPLICATION = re.compile(r'\s*[^\<]\-\>\s*')
>>> EQUIVALENCE = re.compile(r'\s*\<\-\>\s*')
</code></pre>
| 0
|
2009-02-05T04:00:42Z
|
[
"python",
"regex",
"parsing"
] |
Help building a regular expression in python using the re module
| 514,475
|
<p>im writing a simple propositional logic formula parser in python which uses regular expressions re module and the lex/yacc module for lexing/parsing. Originally my code could pick out implication as ->, but adding logical equivalence (<->) caused issues with the compiled expressions</p>
<pre><code>IMPLICATION = re.compile('[\s]*\-\>[\s]*')
EQUIVALENCE = re.compile('[\s]*\<\-\>[\s]*')
...
elif self.IMPLICATION.search(formula[0].strip()):
...
elif self.EQUIVALENCE.search(formula[0].strip()):
...
</code></pre>
<p>I originally tried adding [^<] to the front of -> to make it ignore instances of equivalence but this just made it not accept any instances of implication at all. Any possible help would be warmly welcome :)</p>
| 1
|
2009-02-05T03:51:27Z
| 514,631
|
<p>As far as I can tell, your regular expressions are equivalent to the following:</p>
<pre><code># This is bad, because IMPLICATION also will match every
# string that EQUIVALENCE matches
IMPLICATION = re.compile("->")
EQUIVALENCE = re.compile("<->")
</code></pre>
<p>As you've written it, you're also matching for <em>zero or more</em> whitespace characters before the <code>-></code> and <code><-></code> literal. But you're not capturing the spaces, so it's useless to specify "match whether spaces are present or not". Also, note that <code>-</code> and <code>></code> do not need to be escaped in these regular expressions.</p>
<p>You have two options as I see it. The first is to make sure that <code>IMPLICATION</code> does not match the same strings as <code>EQUIVALENCE</code></p>
<pre><code># This ought to work just fine.
IMPLICATION = re.compile("[^<]->")
EQUIVALENCE = re.compile("<->")
</code></pre>
<p>Another option is to use the <a href="http://en.wikipedia.org/wiki/Maximal_munch" rel="nofollow">maximal munch method</a>; i.e., match against all regular expressions, and choose the longest match. This would resolve ambiguity by giving EQUIVALENCE a higher precedence than IMPLICATION.</p>
| 4
|
2009-02-05T04:59:24Z
|
[
"python",
"regex",
"parsing"
] |
Random name generator strategy - help me improve it
| 514,617
|
<p>I have a small project I am doing in Python using web.py. It's a name generator, using 4 "parts" of a name (<code>firstname, middlename, anothername, surname</code>). Each part of the name is a collection of entites in a MySQL databse (<code>name_part (id, part, type_id)</code>, and <code>name_part_type (id, description)</code>). Basic stuff, I guess.</p>
<p>My generator picks a random entry of each "type", and assembles a comical name. Right now, I am using <code>select * from name_part where type_id=[something] order by rand() limit 1</code> to select a random entry of each type (so I also have 4 queries that run per pageview, I figured this was better than one fat query returning potentially hundreds of rows; if you have a suggestion for how to pull this off in one query w/o a sproc I'll listen).</p>
<p>Obviously I want to make this more random. Actually, I want to give it better coverage, not necessarily randomness. I want to make sure it's using as many possibilities as possible. That's what I am asking in this question, <strong>what sorts of strategies can I use to give coverage over a large random sample</strong>? </p>
<p>My idea, is to implement a counter column on each <code>name_part</code>, and increment it each time I use it. I would need some logic to then say like: "get a name_part that is less than the highest "counter" for this "name_part_type", unless there are none then pick a random one". I am not very good at SQL, is this kind of logic even possible? The only way I can think to do this would require up to 3 or 4 queries for each part of the name (so up to 12 queries per pageview). </p>
<p>Can I get some input on my logic here? Am I overthinking it? This actually sounds ideal for a stored procedure... but can you guys at least help me solve how to do it without a sproc? (I don't know if I can even use a sproc with the built-in database stuff of web.py).</p>
<p>I hope this isn't terribly dumb but thanks ahead of time. </p>
<p>edit: Aside from my specific problem I am still curious if there are any alternate strategies I can use that may be better.</p>
| 4
|
2009-02-05T04:51:24Z
| 514,629
|
<p>I think what you're after is:</p>
<pre><code>select * from name_part
where type_id=[something]
order by used_count asc, rand()
limit 1
</code></pre>
<p>This will put the lesser used names at the top of the list and, if there's multiples with the same (lowest) used_count, they'll sort randomly.</p>
| 4
|
2009-02-05T04:57:45Z
|
[
"python",
"mysql",
"random",
"web.py"
] |
Random name generator strategy - help me improve it
| 514,617
|
<p>I have a small project I am doing in Python using web.py. It's a name generator, using 4 "parts" of a name (<code>firstname, middlename, anothername, surname</code>). Each part of the name is a collection of entites in a MySQL databse (<code>name_part (id, part, type_id)</code>, and <code>name_part_type (id, description)</code>). Basic stuff, I guess.</p>
<p>My generator picks a random entry of each "type", and assembles a comical name. Right now, I am using <code>select * from name_part where type_id=[something] order by rand() limit 1</code> to select a random entry of each type (so I also have 4 queries that run per pageview, I figured this was better than one fat query returning potentially hundreds of rows; if you have a suggestion for how to pull this off in one query w/o a sproc I'll listen).</p>
<p>Obviously I want to make this more random. Actually, I want to give it better coverage, not necessarily randomness. I want to make sure it's using as many possibilities as possible. That's what I am asking in this question, <strong>what sorts of strategies can I use to give coverage over a large random sample</strong>? </p>
<p>My idea, is to implement a counter column on each <code>name_part</code>, and increment it each time I use it. I would need some logic to then say like: "get a name_part that is less than the highest "counter" for this "name_part_type", unless there are none then pick a random one". I am not very good at SQL, is this kind of logic even possible? The only way I can think to do this would require up to 3 or 4 queries for each part of the name (so up to 12 queries per pageview). </p>
<p>Can I get some input on my logic here? Am I overthinking it? This actually sounds ideal for a stored procedure... but can you guys at least help me solve how to do it without a sproc? (I don't know if I can even use a sproc with the built-in database stuff of web.py).</p>
<p>I hope this isn't terribly dumb but thanks ahead of time. </p>
<p>edit: Aside from my specific problem I am still curious if there are any alternate strategies I can use that may be better.</p>
| 4
|
2009-02-05T04:51:24Z
| 514,643
|
<p>I agree with your intuition that using a stored procedure is the right way to go, but then, I almost always try to implement database stuff in the database.</p>
<p>In your proc, I would introduce some kind of logic like say, there's only a 30% chance that returning the result will actually increment the counter. Just to increase the variability.</p>
| 1
|
2009-02-05T05:05:00Z
|
[
"python",
"mysql",
"random",
"web.py"
] |
Translating Python Regexp to Shell
| 514,767
|
<p>I'm writing an Applescript playlist generator. Part of the process is to read the iTunes Library XML file to get a list of all of the genres in a user's library. This is the python implementation, which works as I'd like:</p>
<pre><code> #!/usr/bin/env python
# script to get all of the genres from itunes
import re,sys,sets
## Boosted from the internet to handle HTML entities in Genre names
def unescape(text):
def fixup(m):
text = m.group(0)
if text[:2] == "&#":
# character reference
try:
if text[:3] == "&#x":
return unichr(int(text[3:-1], 16))
else:
return unichr(int(text[2:-1]))
except ValueError:
pass
else:
# named entity
try:
text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
except KeyError:
pass
return text # leave as is
return re.sub("&#?\w+;", fixup, text)
# probably faster to use a regex than to try to walk
# the entire xml document and aggregate the genres
try:
xml_path = "/Users/%s/Music/iTunes/iTunes Music Library.xml" % sys.argv[1]
except:
print '\tUsage: python '+sys.argv[0]+' <your OSX username>'
raise SystemExit
pattern = "<key>Genre</key><string>([^<]+)</string>"
try:
xml = file(xml_path,'r').read()
except:
print '\tUnable to load your iTunes Library XML file'
raise SystemExit
matches = re.findall(pattern,xml)
uniques = map(unescape,list(sets.Set(matches)))
## need to write these out somewhere so the applescript can read them
sys.stdout.write('|'.join(uniques))
raise SystemExit
</code></pre>
<p>The problem is, I'd like the Applescript to be self-contained and not require that this additional file be present (I plan on making this available to other people). And, as far as I can tell, Applescript doesn't offer any type of regular expression capabilities out of the box. I could loop over each track in the library to get all of the genres, but this is a prohibitively long process that I already do once when building the playlist. So, I'm looking for alternatives.</p>
<p>Since Applescript allows me to run a shell script and capture the results, I imagine that I can accomplish the same behavior using some type of shell command, be it grep, perl, or something else. My *nix command line skills are extremely rusty and I'm looking for some guidance.</p>
<p>So, in short, I'd like to find a way to translate the above python code into something I can call directly from the shell and get a similar result. Thanks!</p>
| 1
|
2009-02-05T06:10:39Z
| 514,919
|
<p>Why are you using regex to parse XML? Why not use a proper XML library? Python has some great utilities like ElementTree that make walking the DOM a lot easier, and it yields nice, friendly objects rather than untyped strings.</p>
<p>Here are some ways of parsing XML using Applescript:</p>
<p><a href="http://lists.apple.com/archives/AppleScript-Studio/2005/Sep/msg00114.html" rel="nofollow">Applescript XML Parser</a> (Available since Tiger apparently)</p>
<p><a href="http://www.latenightsw.com/freeware/XMLTools2/" rel="nofollow">XML Tools you can also use with Applescript</a></p>
<p>Remember, just like Applescript can hook into iTunes, it can hook into other installed utilities like these.</p>
<p>Lastly, why not just write the whole thing in Python since it has way better development tools for debugging and runs a lot faster. If you're running Leopard, you have Python 2.5.1 pre-installed.</p>
| 3
|
2009-02-05T07:30:52Z
|
[
"python",
"applescript"
] |
Translating Python Regexp to Shell
| 514,767
|
<p>I'm writing an Applescript playlist generator. Part of the process is to read the iTunes Library XML file to get a list of all of the genres in a user's library. This is the python implementation, which works as I'd like:</p>
<pre><code> #!/usr/bin/env python
# script to get all of the genres from itunes
import re,sys,sets
## Boosted from the internet to handle HTML entities in Genre names
def unescape(text):
def fixup(m):
text = m.group(0)
if text[:2] == "&#":
# character reference
try:
if text[:3] == "&#x":
return unichr(int(text[3:-1], 16))
else:
return unichr(int(text[2:-1]))
except ValueError:
pass
else:
# named entity
try:
text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
except KeyError:
pass
return text # leave as is
return re.sub("&#?\w+;", fixup, text)
# probably faster to use a regex than to try to walk
# the entire xml document and aggregate the genres
try:
xml_path = "/Users/%s/Music/iTunes/iTunes Music Library.xml" % sys.argv[1]
except:
print '\tUsage: python '+sys.argv[0]+' <your OSX username>'
raise SystemExit
pattern = "<key>Genre</key><string>([^<]+)</string>"
try:
xml = file(xml_path,'r').read()
except:
print '\tUnable to load your iTunes Library XML file'
raise SystemExit
matches = re.findall(pattern,xml)
uniques = map(unescape,list(sets.Set(matches)))
## need to write these out somewhere so the applescript can read them
sys.stdout.write('|'.join(uniques))
raise SystemExit
</code></pre>
<p>The problem is, I'd like the Applescript to be self-contained and not require that this additional file be present (I plan on making this available to other people). And, as far as I can tell, Applescript doesn't offer any type of regular expression capabilities out of the box. I could loop over each track in the library to get all of the genres, but this is a prohibitively long process that I already do once when building the playlist. So, I'm looking for alternatives.</p>
<p>Since Applescript allows me to run a shell script and capture the results, I imagine that I can accomplish the same behavior using some type of shell command, be it grep, perl, or something else. My *nix command line skills are extremely rusty and I'm looking for some guidance.</p>
<p>So, in short, I'd like to find a way to translate the above python code into something I can call directly from the shell and get a similar result. Thanks!</p>
| 1
|
2009-02-05T06:10:39Z
| 515,599
|
<p>Is creating a standalone App the Solution ?</p>
<p>Look at py2app:</p>
<p>py2app, works like py2exe but targets Mac OS</p>
<p><a href="http://stackoverflow.com/questions/2933/an-executable-python-app">See</a></p>
| 0
|
2009-02-05T11:58:02Z
|
[
"python",
"applescript"
] |
Translating Python Regexp to Shell
| 514,767
|
<p>I'm writing an Applescript playlist generator. Part of the process is to read the iTunes Library XML file to get a list of all of the genres in a user's library. This is the python implementation, which works as I'd like:</p>
<pre><code> #!/usr/bin/env python
# script to get all of the genres from itunes
import re,sys,sets
## Boosted from the internet to handle HTML entities in Genre names
def unescape(text):
def fixup(m):
text = m.group(0)
if text[:2] == "&#":
# character reference
try:
if text[:3] == "&#x":
return unichr(int(text[3:-1], 16))
else:
return unichr(int(text[2:-1]))
except ValueError:
pass
else:
# named entity
try:
text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
except KeyError:
pass
return text # leave as is
return re.sub("&#?\w+;", fixup, text)
# probably faster to use a regex than to try to walk
# the entire xml document and aggregate the genres
try:
xml_path = "/Users/%s/Music/iTunes/iTunes Music Library.xml" % sys.argv[1]
except:
print '\tUsage: python '+sys.argv[0]+' <your OSX username>'
raise SystemExit
pattern = "<key>Genre</key><string>([^<]+)</string>"
try:
xml = file(xml_path,'r').read()
except:
print '\tUnable to load your iTunes Library XML file'
raise SystemExit
matches = re.findall(pattern,xml)
uniques = map(unescape,list(sets.Set(matches)))
## need to write these out somewhere so the applescript can read them
sys.stdout.write('|'.join(uniques))
raise SystemExit
</code></pre>
<p>The problem is, I'd like the Applescript to be self-contained and not require that this additional file be present (I plan on making this available to other people). And, as far as I can tell, Applescript doesn't offer any type of regular expression capabilities out of the box. I could loop over each track in the library to get all of the genres, but this is a prohibitively long process that I already do once when building the playlist. So, I'm looking for alternatives.</p>
<p>Since Applescript allows me to run a shell script and capture the results, I imagine that I can accomplish the same behavior using some type of shell command, be it grep, perl, or something else. My *nix command line skills are extremely rusty and I'm looking for some guidance.</p>
<p>So, in short, I'd like to find a way to translate the above python code into something I can call directly from the shell and get a similar result. Thanks!</p>
| 1
|
2009-02-05T06:10:39Z
| 525,605
|
<p>If you're already working in AppleScript, why not just ask iTunes directly?</p>
<pre><code>tell application "iTunes" to get genre of every track of library playlist 1
</code></pre>
| 0
|
2009-02-08T12:13:07Z
|
[
"python",
"applescript"
] |
Web based wizard with Python
| 514,912
|
<p>What is a good/simple way to create, say a five page wizard, in Python, where the web server component composes the wizard page content mostly dynamically by fetching the data via calls to a XML-RPC back-end. I have experienced a bit with the XML-RPC Python module, but I don't know which Python module would be providing the web server, how to create the static content for the wizard and I don't know how to extend the web server component to make the XML-RPC calls from the web server to the XML-RPC back-end to be able to create the dynamic content.</p>
| 2
|
2009-02-05T07:27:05Z
| 515,077
|
<p>If we break down to the components you'll need, we get:</p>
<ol>
<li>HTTP server to receive the request from the clients browser.</li>
<li>A URL router to look at the URL sent from client browser and call your function/method to handle that URL.</li>
<li>An XML-RPC client library to fetch the data for that URL.</li>
<li>A template processor to render the fetched data into HTML.</li>
<li>A way to send the rendered HTML as a response back to the client browser.</li>
</ol>
<p>These components are handled by almost all, if not all, Python web frameworks. The XML-RPC client might be missing, but you can just use the standard Python module you already know.</p>
<p><a href="http://www.djangoproject.com/" rel="nofollow">Django</a> and <a href="http://pylonshq.com/" rel="nofollow">Pylons</a> are well documented and can easily handle this kind of project, but they will also have a lot of stuff you won't need. If you want very easy and absolute minimum take a look at using <a href="http://github.com/breily/juno/tree/master" rel="nofollow">juno</a>, which was just released recently and is getting some buzz.</p>
<p>These frameworks will handle #1 and provide a way for you to specify #2, so then you need to write your function/method that handles the incoming request (in Django this is called a 'view').</p>
<p>All you would do is fetch your data via XML-RPC, populate a dictionary with that data (in Django this dictionary is referred to as 'context') and then render a template from the context into HTML by calling the template engine for that framework.</p>
<p>Your function will just return the HTML to the framework which will then format it properly as an HTTP response and send it back to the client browser.</p>
<p>Simple!</p>
<p>UPDATE: Here's a description of how to do wizard style <a href="http://superjared.com/entry/formwizard-multiple-step-forms-django/" rel="nofollow">multiple-step forms in Django</a> that should help you out.</p>
| 3
|
2009-02-05T08:51:02Z
|
[
"python",
"xml-rpc",
"wizard"
] |
How best to pass database objects to a turbogears WidgetList?
| 515,522
|
<p>I am trying to set up form widgets for adding some objects to the database but I'm getting stuck because it seems impossible to pass any arguments to Widgets contained within a WidgetList. To clarify that, here is my WidgetList:</p>
<pre><code>class ClientFields(forms.WidgetsList):
"""Form to create a client"""
name = forms.TextField(validator=validators.NotEmpty())
abbreviated = forms.TextField(validator=validators.NotEmpty(), attrs={'size':2})
address = forms.TextArea(validator=validators.NotEmpty())
country = forms.TextField(validator=validators.NotEmpty())
vat_number = forms.TextField(validator=validators.NotEmpty())
email_address = forms.TextField(validator=validators.Email(not_empty=True))
client_group = forms.SingleSelectField(validator=validators.NotEmpty(),
options=[(g.id, g.name) for g in ClientGroup.all_client_groups().all()])
</code></pre>
<p>You see I have had to resort to grabbing objects from the database from within the WidgetList, which means that it's rather tightly coupled with the database code (even though it's using a classmethod in the model). </p>
<p>The problem is that once the WidgetList instance is created, you can't access those fields (otherwise I could just call client_fields.client_group.options=[(key,value)] from the controller) - the fields are removed from the class and added to a list, so to find them again, I'd have to iterate through that list to find the Field class I want to alter - not clean. Here's the output from ipython as I check out the WidgetsList:</p>
<pre>In [8]: mad.declared_widgets
Out[8]:
[TextField(name='name', attrs={}, field_class='textfield', css_classes=[], convert=True),
TextField(name='abbreveated', attrs={'size': 2}, field_class='textfield', css_classes=[], convert=True),
TextArea(name='address', rows=7, cols=50, attrs={}, field_class='textarea', css_classes=[], convert=True),
TextField(name='country', attrs={}, field_class='textfield', css_classes=[], convert=True),
TextField(name='vat_number', attrs={}, field_class='textfield', css_classes=[], convert=True),
TextField(name='email_address', attrs={}, field_class='textfield', css_classes=[], convert=True),
SingleSelectField(name='client_group', attrs={}, options=[(1, u"Proporta's Clients")], field_class='singleselectfield', css_classes=[], convert=False)]</pre>
<p>So...what would be the right way to set these Widgets and WidgetLists up without coupling them too tightly to the database and so on?</p>
| 1
|
2009-02-05T11:35:01Z
| 515,689
|
<p>A <a href="http://docs.turbogears.org/1.0/SimpleWidgetForm" rel="nofollow">page in the TurboGears documentation</a> may help.</p>
| 0
|
2009-02-05T12:26:02Z
|
[
"python",
"turbogears"
] |
Detect key press combination in Linux with Python?
| 515,801
|
<p>I'm trying to capture key presses so that when a given combination is pressed I trigger an event.</p>
<p>I've searched around for tips on how to get started and the simplest code snippet I can find is in Python - I grabbed the code below for it from <a href="http://www.daniweb.com/forums/thread112975.html" rel="nofollow">here</a>. However, when I run this from a terminal and hit some keys, after the "Press a key..." statement nothing happens. </p>
<p>Am I being stupid? Can anyone explain why nothing happens, or suggest a better way of achieving this on Linux (any language considered!)?</p>
<pre><code>import Tkinter as tk
def key(event):
if event.keysym == 'Escape':
root.destroy()
print event.char
root = tk.Tk()
print "Press a key (Escape key to exit):"
root.bind_all('<Key>', key)
# don't show the tk window
root.withdraw()
root.mainloop()
</code></pre>
| 4
|
2009-02-05T13:03:36Z
| 515,835
|
<p>Tk does not seem to get it if you do not display the window. Try:</p>
<pre><code>import Tkinter as tk
def key(event):
if event.keysym == 'Escape':
root.destroy()
print event.char
root = tk.Tk()
print "Press a key (Escape key to exit):"
root.bind_all('<Key>', key)
# don't show the tk window
# root.withdraw()
root.mainloop()
</code></pre>
<p>works for me...</p>
| 3
|
2009-02-05T13:12:09Z
|
[
"python",
"linux",
"keylogger"
] |
Detect key press combination in Linux with Python?
| 515,801
|
<p>I'm trying to capture key presses so that when a given combination is pressed I trigger an event.</p>
<p>I've searched around for tips on how to get started and the simplest code snippet I can find is in Python - I grabbed the code below for it from <a href="http://www.daniweb.com/forums/thread112975.html" rel="nofollow">here</a>. However, when I run this from a terminal and hit some keys, after the "Press a key..." statement nothing happens. </p>
<p>Am I being stupid? Can anyone explain why nothing happens, or suggest a better way of achieving this on Linux (any language considered!)?</p>
<pre><code>import Tkinter as tk
def key(event):
if event.keysym == 'Escape':
root.destroy()
print event.char
root = tk.Tk()
print "Press a key (Escape key to exit):"
root.bind_all('<Key>', key)
# don't show the tk window
root.withdraw()
root.mainloop()
</code></pre>
| 4
|
2009-02-05T13:03:36Z
| 515,878
|
<p>What you're doing is reading <code>/dev/tty</code> in "raw" mode.</p>
<p>Normal Linux input is "cooked" -- backspaces and line endings have been handled for you.</p>
<p>To read a device like your keyboard in "raw" mode, you need to make direct Linux API calls to IOCTL.</p>
<p>Look at <a href="http://code.activestate.com/recipes/68397/" rel="nofollow">http://code.activestate.com/recipes/68397/</a> for some guidance on this. Yes, the recipe is in tcl, but it gives you a hint as to how to proceed.</p>
| 1
|
2009-02-05T13:26:15Z
|
[
"python",
"linux",
"keylogger"
] |
Detect key press combination in Linux with Python?
| 515,801
|
<p>I'm trying to capture key presses so that when a given combination is pressed I trigger an event.</p>
<p>I've searched around for tips on how to get started and the simplest code snippet I can find is in Python - I grabbed the code below for it from <a href="http://www.daniweb.com/forums/thread112975.html" rel="nofollow">here</a>. However, when I run this from a terminal and hit some keys, after the "Press a key..." statement nothing happens. </p>
<p>Am I being stupid? Can anyone explain why nothing happens, or suggest a better way of achieving this on Linux (any language considered!)?</p>
<pre><code>import Tkinter as tk
def key(event):
if event.keysym == 'Escape':
root.destroy()
print event.char
root = tk.Tk()
print "Press a key (Escape key to exit):"
root.bind_all('<Key>', key)
# don't show the tk window
root.withdraw()
root.mainloop()
</code></pre>
| 4
|
2009-02-05T13:03:36Z
| 516,064
|
<p>Well, turns out there is a much simpler answer when using GNOME which doesn't involve any programming at all...</p>
<p><a href="http://www.captain.at/howto-gnome-custom-hotkey-keyboard-shortcut.php" rel="nofollow">http://www.captain.at/howto-gnome-custom-hotkey-keyboard-shortcut.php</a></p>
<p><a href="https://web.archive.org/web/20070802112319/http://www.captain.at/howto-gnome-custom-hotkey-keyboard-shortcut.php" rel="nofollow">Archived on Wayback</a></p>
<p>Just create the script/executable to be triggered by the key combination and point the 'keybinding_commands' entry you create in gconf-editor at it. </p>
<p>Why didn't I think of that earlier?</p>
| 1
|
2009-02-05T14:16:27Z
|
[
"python",
"linux",
"keylogger"
] |
Detect key press combination in Linux with Python?
| 515,801
|
<p>I'm trying to capture key presses so that when a given combination is pressed I trigger an event.</p>
<p>I've searched around for tips on how to get started and the simplest code snippet I can find is in Python - I grabbed the code below for it from <a href="http://www.daniweb.com/forums/thread112975.html" rel="nofollow">here</a>. However, when I run this from a terminal and hit some keys, after the "Press a key..." statement nothing happens. </p>
<p>Am I being stupid? Can anyone explain why nothing happens, or suggest a better way of achieving this on Linux (any language considered!)?</p>
<pre><code>import Tkinter as tk
def key(event):
if event.keysym == 'Escape':
root.destroy()
print event.char
root = tk.Tk()
print "Press a key (Escape key to exit):"
root.bind_all('<Key>', key)
# don't show the tk window
root.withdraw()
root.mainloop()
</code></pre>
| 4
|
2009-02-05T13:03:36Z
| 2,048,434
|
<p>Alternatively (a non-Python option) use <a href="http://www.nongnu.org/xbindkeys/xbindkeys.html" rel="nofollow">XBindKeys</a>.</p>
| 1
|
2010-01-12T11:14:22Z
|
[
"python",
"linux",
"keylogger"
] |
Most pythonic way to extend a potentially incomplete list
| 516,039
|
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p>
<p>An example transformation would be</p>
<pre><code>['a','b',None,'c']
</code></pre>
<p>to</p>
<pre><code>['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']
</code></pre>
<p>My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well:</p>
<pre><code>def extendChoices(cList):
for i in range(0,9):
try:
if cList[i] is None:
cList[i] = "Choice %d"%(i+1)
except IndexError:
cList.append("Choice %d"%(i+1)
</code></pre>
<p>and</p>
<pre><code>def extendChoices(cList):
# Fill in any blank entries
for i, v in enumerate(cList):
cList[i] = v or "Choice %s" % (i+1)
# Extend the list to 9 choices
for j in range(len(cList)+1, 10):
cList.append("Choice %s" % (j))
</code></pre>
<p>I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.</p>
| 6
|
2009-02-05T14:11:32Z
| 516,070
|
<p>I think I'd do something pretty much like that, but with a few tidy ups:</p>
<pre><code>for i in range(0,10):
try:
if choicesTxt[i] is None:
choicesTxt[i] = "Choice %d"%i
except IndexError:
choicesTxt.append("Choice %d"%i)
</code></pre>
<p>Of which the only important two are to only catch <code>IndexError</code> rather than any exception, and to index from 0.</p>
<p>And the only real problem with the original would be if <code>choicesTxt</code> is empty, when the choices added will be off by one.</p>
| 3
|
2009-02-05T14:17:39Z
|
[
"python"
] |
Most pythonic way to extend a potentially incomplete list
| 516,039
|
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p>
<p>An example transformation would be</p>
<pre><code>['a','b',None,'c']
</code></pre>
<p>to</p>
<pre><code>['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']
</code></pre>
<p>My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well:</p>
<pre><code>def extendChoices(cList):
for i in range(0,9):
try:
if cList[i] is None:
cList[i] = "Choice %d"%(i+1)
except IndexError:
cList.append("Choice %d"%(i+1)
</code></pre>
<p>and</p>
<pre><code>def extendChoices(cList):
# Fill in any blank entries
for i, v in enumerate(cList):
cList[i] = v or "Choice %s" % (i+1)
# Extend the list to 9 choices
for j in range(len(cList)+1, 10):
cList.append("Choice %s" % (j))
</code></pre>
<p>I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.</p>
| 6
|
2009-02-05T14:11:32Z
| 516,093
|
<p>I think you should treat resizing the array as a separate step. To do so, in the case the array is too short, call <code>choicesTxt=choicesTxt+[None]*(10-len(choicesTxt))</code>.
The <code>None</code> choice reasignment can be done using list comprehensions.</p>
| 2
|
2009-02-05T14:22:01Z
|
[
"python"
] |
Most pythonic way to extend a potentially incomplete list
| 516,039
|
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p>
<p>An example transformation would be</p>
<pre><code>['a','b',None,'c']
</code></pre>
<p>to</p>
<pre><code>['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']
</code></pre>
<p>My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well:</p>
<pre><code>def extendChoices(cList):
for i in range(0,9):
try:
if cList[i] is None:
cList[i] = "Choice %d"%(i+1)
except IndexError:
cList.append("Choice %d"%(i+1)
</code></pre>
<p>and</p>
<pre><code>def extendChoices(cList):
# Fill in any blank entries
for i, v in enumerate(cList):
cList[i] = v or "Choice %s" % (i+1)
# Extend the list to 9 choices
for j in range(len(cList)+1, 10):
cList.append("Choice %s" % (j))
</code></pre>
<p>I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.</p>
| 6
|
2009-02-05T14:11:32Z
| 516,094
|
<p>I would also recommend using xrange instead of range. The xrange function generates the numbers as needed. Range generates them in advance. For small sets it doesn't make much difference, but for large ranges the savings can be huge.</p>
| 0
|
2009-02-05T14:22:05Z
|
[
"python"
] |
Most pythonic way to extend a potentially incomplete list
| 516,039
|
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p>
<p>An example transformation would be</p>
<pre><code>['a','b',None,'c']
</code></pre>
<p>to</p>
<pre><code>['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']
</code></pre>
<p>My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well:</p>
<pre><code>def extendChoices(cList):
for i in range(0,9):
try:
if cList[i] is None:
cList[i] = "Choice %d"%(i+1)
except IndexError:
cList.append("Choice %d"%(i+1)
</code></pre>
<p>and</p>
<pre><code>def extendChoices(cList):
# Fill in any blank entries
for i, v in enumerate(cList):
cList[i] = v or "Choice %s" % (i+1)
# Extend the list to 9 choices
for j in range(len(cList)+1, 10):
cList.append("Choice %s" % (j))
</code></pre>
<p>I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.</p>
| 6
|
2009-02-05T14:11:32Z
| 516,116
|
<p>What about that (seems to be a dict -- not a list -- when it's <em>incomplete</em>)</p>
<pre><code>a = {1:'a', 2:None, 5:'e'} #test data
[a[x] if x in a and a[x] is not None else 'Choice %d'%x for x in xrange(1,10)]
</code></pre>
<p>Edit once more: If it's really a list (not a dict):</p>
<pre><code>b=['a',None,'b']
[b[x] if len(b)>x and b[x] is not None else 'Choice %d'%x for x in xrange(10)]
</code></pre>
<p>needs Python 2.5 I think (because of the ternary operator)?</p>
<p>(Thanks to joeforker fixed that it uses keys 1 to 10 and not 0 to 10 anymore; thanks to SilentGhost: in is more pythonic than has_key() or len())</p>
| 1
|
2009-02-05T14:28:08Z
|
[
"python"
] |
Most pythonic way to extend a potentially incomplete list
| 516,039
|
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p>
<p>An example transformation would be</p>
<pre><code>['a','b',None,'c']
</code></pre>
<p>to</p>
<pre><code>['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']
</code></pre>
<p>My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well:</p>
<pre><code>def extendChoices(cList):
for i in range(0,9):
try:
if cList[i] is None:
cList[i] = "Choice %d"%(i+1)
except IndexError:
cList.append("Choice %d"%(i+1)
</code></pre>
<p>and</p>
<pre><code>def extendChoices(cList):
# Fill in any blank entries
for i, v in enumerate(cList):
cList[i] = v or "Choice %s" % (i+1)
# Extend the list to 9 choices
for j in range(len(cList)+1, 10):
cList.append("Choice %s" % (j))
</code></pre>
<p>I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.</p>
| 6
|
2009-02-05T14:11:32Z
| 516,121
|
<p>If you don't mind replacing anything that evaluates to False with "Choice %d", then <code>result</code> works for Python 2.4.</p>
<p>If you do mind and have Python 2.5 and above then use <code>result2_5_plus</code> with the power of ternary <code>if</code>.</p>
<p>If you don't like or can't use ternary if, then take advantage of the fact that <code>True == 1</code> and <code>False == 0</code>, using the result of <code>x is None</code> to index a list.</p>
<pre><code>x = ["Blue", None, 0, "", "No, Yelloooow!"]
y = [None]*9
result = [(t or "Choice %d" % (i+1))\
for i, t in enumerate(x + y[len(x):])]
result2_5_plus = [(t if t is not None else "Choice %d" % (i+1))\
for i, t in enumerate(x + y[len(x):])]
result_no_ternary_if = [[t, "Choice %d" % (i+1)][t is None]\
for i, t in enumerate(x + y[len(x):])]
['Blue', 'Choice 2', 'Choice 3', 'Choice 4', 'No, Yelloooow!', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9']
['Blue', 'Choice 2', 0, '', 'No, Yelloooow!', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9']
</code></pre>
| 1
|
2009-02-05T14:29:56Z
|
[
"python"
] |
Most pythonic way to extend a potentially incomplete list
| 516,039
|
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p>
<p>An example transformation would be</p>
<pre><code>['a','b',None,'c']
</code></pre>
<p>to</p>
<pre><code>['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']
</code></pre>
<p>My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well:</p>
<pre><code>def extendChoices(cList):
for i in range(0,9):
try:
if cList[i] is None:
cList[i] = "Choice %d"%(i+1)
except IndexError:
cList.append("Choice %d"%(i+1)
</code></pre>
<p>and</p>
<pre><code>def extendChoices(cList):
# Fill in any blank entries
for i, v in enumerate(cList):
cList[i] = v or "Choice %s" % (i+1)
# Extend the list to 9 choices
for j in range(len(cList)+1, 10):
cList.append("Choice %s" % (j))
</code></pre>
<p>I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.</p>
| 6
|
2009-02-05T14:11:32Z
| 516,129
|
<p>My initial reaction was to split the list extension and "filling in the blanks" into separate parts as so:</p>
<pre><code>for i, v in enumerate(my_list):
my_list[i] = v or "Choice %s" % (i+1)
for j in range(len(my_list)+1, 10):
my_list.append("Choice %s" % (j))
# maybe this is nicer for the extension?
while len(my_list) < 10:
my_list.append("Choice %s" % (len(my_list)+1))
</code></pre>
<p>If you do stick with the <code>try...except</code> approach, do catch a specific exception as <a href="http://stackoverflow.com/questions/516039/most-pythonic-way-to-extend-a-potentially-incomplete-list/516070#516070">Douglas</a> shows. Otherwise, you'll catch <strong>everything</strong>: <code>KeyboardInterrupts</code>, <code>RuntimeErrors</code>, <code>SyntaxErrors</code>, ... . You do not want to do that.</p>
<p><strong>EDIT:</strong> fixed 1-indexed list error - thanks <a href="http://stackoverflow.com/users/51025/dns">DNS</a>!</p>
<p><strong>EDIT:</strong> added alternative list extension</p>
| 7
|
2009-02-05T14:31:59Z
|
[
"python"
] |
Most pythonic way to extend a potentially incomplete list
| 516,039
|
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p>
<p>An example transformation would be</p>
<pre><code>['a','b',None,'c']
</code></pre>
<p>to</p>
<pre><code>['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']
</code></pre>
<p>My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well:</p>
<pre><code>def extendChoices(cList):
for i in range(0,9):
try:
if cList[i] is None:
cList[i] = "Choice %d"%(i+1)
except IndexError:
cList.append("Choice %d"%(i+1)
</code></pre>
<p>and</p>
<pre><code>def extendChoices(cList):
# Fill in any blank entries
for i, v in enumerate(cList):
cList[i] = v or "Choice %s" % (i+1)
# Extend the list to 9 choices
for j in range(len(cList)+1, 10):
cList.append("Choice %s" % (j))
</code></pre>
<p>I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.</p>
| 6
|
2009-02-05T14:11:32Z
| 516,138
|
<pre><code>>>> in_list = ["a","b",None,"c"]
>>> new = ['choice ' + str(i + 1) if j is None else j for i, j in enumerate(in_list)]
>>> new.extend(('choice ' +str(i + 1) for i in range(len(new), 9)))
>>> new
['a', 'b', 'choice 3', 'c', 'choice 5', 'choice 6', 'choice 7', 'choice 8', 'choice 9']
</code></pre>
| 0
|
2009-02-05T14:36:01Z
|
[
"python"
] |
Most pythonic way to extend a potentially incomplete list
| 516,039
|
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p>
<p>An example transformation would be</p>
<pre><code>['a','b',None,'c']
</code></pre>
<p>to</p>
<pre><code>['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']
</code></pre>
<p>My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well:</p>
<pre><code>def extendChoices(cList):
for i in range(0,9):
try:
if cList[i] is None:
cList[i] = "Choice %d"%(i+1)
except IndexError:
cList.append("Choice %d"%(i+1)
</code></pre>
<p>and</p>
<pre><code>def extendChoices(cList):
# Fill in any blank entries
for i, v in enumerate(cList):
cList[i] = v or "Choice %s" % (i+1)
# Extend the list to 9 choices
for j in range(len(cList)+1, 10):
cList.append("Choice %s" % (j))
</code></pre>
<p>I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.</p>
| 6
|
2009-02-05T14:11:32Z
| 516,144
|
<p>You could use map (dictionary) instead of list:</p>
<pre><code>choices_map = {1:'Choice 1', 2:'Choice 2', 3:'Choice 12'}
for key in xrange(1, 10):
choices_map.setdefault(key, 'Choice %d'%key)
</code></pre>
<p>Then you have map filled with your data.<br />
If you want a list instead you can do: </p>
<pre><code>choices = choices_map.values()
choices.sort() #if you want your list to be sorted
#In Python 2.5 and newer you can do:
choices = [choices_map[k] for k in sorted(choices_map)]
</code></pre>
| 3
|
2009-02-05T14:36:36Z
|
[
"python"
] |
Most pythonic way to extend a potentially incomplete list
| 516,039
|
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p>
<p>An example transformation would be</p>
<pre><code>['a','b',None,'c']
</code></pre>
<p>to</p>
<pre><code>['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']
</code></pre>
<p>My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well:</p>
<pre><code>def extendChoices(cList):
for i in range(0,9):
try:
if cList[i] is None:
cList[i] = "Choice %d"%(i+1)
except IndexError:
cList.append("Choice %d"%(i+1)
</code></pre>
<p>and</p>
<pre><code>def extendChoices(cList):
# Fill in any blank entries
for i, v in enumerate(cList):
cList[i] = v or "Choice %s" % (i+1)
# Extend the list to 9 choices
for j in range(len(cList)+1, 10):
cList.append("Choice %s" % (j))
</code></pre>
<p>I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.</p>
| 6
|
2009-02-05T14:11:32Z
| 516,170
|
<p>I'm a little unclear about why you're using range(1, 10); since you're using choicesTxt[i], that ends up skipping the None check for the first element in your list.</p>
<p>Also, there are obviously easier ways to do this if you're creating a new list, but you're asking specifically to add to an existing list.</p>
<p>I don't think this is really cleaner or faster, but it's a different idea for you to think about.</p>
<pre><code>for i, v in enumerate(choicesTxt):
choicesTxt[i] = v or "Choice " + str(i + 1)
choicesTxt.extend([ "Choice " + str(i) for i in range(len(choicesTxt) + 1, 10) ])
</code></pre>
| 1
|
2009-02-05T14:40:38Z
|
[
"python"
] |
Most pythonic way to extend a potentially incomplete list
| 516,039
|
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p>
<p>An example transformation would be</p>
<pre><code>['a','b',None,'c']
</code></pre>
<p>to</p>
<pre><code>['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']
</code></pre>
<p>My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well:</p>
<pre><code>def extendChoices(cList):
for i in range(0,9):
try:
if cList[i] is None:
cList[i] = "Choice %d"%(i+1)
except IndexError:
cList.append("Choice %d"%(i+1)
</code></pre>
<p>and</p>
<pre><code>def extendChoices(cList):
# Fill in any blank entries
for i, v in enumerate(cList):
cList[i] = v or "Choice %s" % (i+1)
# Extend the list to 9 choices
for j in range(len(cList)+1, 10):
cList.append("Choice %s" % (j))
</code></pre>
<p>I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.</p>
| 6
|
2009-02-05T14:11:32Z
| 516,241
|
<p>I would do</p>
<pre><code>for i, c in enumerate(choices):
if c is None:
choices[i] = 'Choice X'
choices += ['Choice %d' % (i+1) for i in range(len(choices), 10)]
</code></pre>
<p>which only replaces actual <code>None</code> values (not anything that evaluates as false), and extends the list in a separated step which I think is clearer.</p>
| 1
|
2009-02-05T15:01:08Z
|
[
"python"
] |
Most pythonic way to extend a potentially incomplete list
| 516,039
|
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p>
<p>An example transformation would be</p>
<pre><code>['a','b',None,'c']
</code></pre>
<p>to</p>
<pre><code>['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']
</code></pre>
<p>My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well:</p>
<pre><code>def extendChoices(cList):
for i in range(0,9):
try:
if cList[i] is None:
cList[i] = "Choice %d"%(i+1)
except IndexError:
cList.append("Choice %d"%(i+1)
</code></pre>
<p>and</p>
<pre><code>def extendChoices(cList):
# Fill in any blank entries
for i, v in enumerate(cList):
cList[i] = v or "Choice %s" % (i+1)
# Extend the list to 9 choices
for j in range(len(cList)+1, 10):
cList.append("Choice %s" % (j))
</code></pre>
<p>I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.</p>
| 6
|
2009-02-05T14:11:32Z
| 516,266
|
<p>I find that when list comprehensions get long it's better to just use a standard for loop.
Nearly the same as others but anyway:</p>
<pre><code>>>> in_list = ["a","b",None,"c"]
>>> full_list = in_list + ([None] * (10 - len(in_list)))
>>> for idx, value in enumerate(full_list):
... if value == None:
... full_list[idx] = 'Choice %d' % (idx + 1)
...
>>> full_list
['a', 'b', 'Choice 3', 'c', 'Choice 5', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9', 'Choice 10']
</code></pre>
| 1
|
2009-02-05T15:07:41Z
|
[
"python"
] |
Most pythonic way to extend a potentially incomplete list
| 516,039
|
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p>
<p>An example transformation would be</p>
<pre><code>['a','b',None,'c']
</code></pre>
<p>to</p>
<pre><code>['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']
</code></pre>
<p>My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well:</p>
<pre><code>def extendChoices(cList):
for i in range(0,9):
try:
if cList[i] is None:
cList[i] = "Choice %d"%(i+1)
except IndexError:
cList.append("Choice %d"%(i+1)
</code></pre>
<p>and</p>
<pre><code>def extendChoices(cList):
# Fill in any blank entries
for i, v in enumerate(cList):
cList[i] = v or "Choice %s" % (i+1)
# Extend the list to 9 choices
for j in range(len(cList)+1, 10):
cList.append("Choice %s" % (j))
</code></pre>
<p>I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.</p>
| 6
|
2009-02-05T14:11:32Z
| 516,279
|
<pre><code>choices[:] = ([{False: x, True: "Choice %d" % (i + 1)}[x is None] for i, x in enumerate(choices)] +
["Choice %d" % (i + 1) for i in xrange(len(choices), 9)])
</code></pre>
| 1
|
2009-02-05T15:10:46Z
|
[
"python"
] |
Most pythonic way to extend a potentially incomplete list
| 516,039
|
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p>
<p>An example transformation would be</p>
<pre><code>['a','b',None,'c']
</code></pre>
<p>to</p>
<pre><code>['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']
</code></pre>
<p>My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well:</p>
<pre><code>def extendChoices(cList):
for i in range(0,9):
try:
if cList[i] is None:
cList[i] = "Choice %d"%(i+1)
except IndexError:
cList.append("Choice %d"%(i+1)
</code></pre>
<p>and</p>
<pre><code>def extendChoices(cList):
# Fill in any blank entries
for i, v in enumerate(cList):
cList[i] = v or "Choice %s" % (i+1)
# Extend the list to 9 choices
for j in range(len(cList)+1, 10):
cList.append("Choice %s" % (j))
</code></pre>
<p>I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.</p>
| 6
|
2009-02-05T14:11:32Z
| 516,349
|
<p>You could go simpler with a list comprehension:</p>
<pre><code>extendedChoices = choices + ([None] * (10 - len(choices)))
newChoices = ["Choice %d" % (i+1) if x is None else x
for i, x in enumerate(extendedChoices)]
</code></pre>
<p>This appends <code>None</code> to your choices list until it has at least 10 items, enumerates through the result, and inserts "Choice X" if the Xth element is missing.</p>
| 1
|
2009-02-05T15:25:20Z
|
[
"python"
] |
Most pythonic way to extend a potentially incomplete list
| 516,039
|
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p>
<p>An example transformation would be</p>
<pre><code>['a','b',None,'c']
</code></pre>
<p>to</p>
<pre><code>['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']
</code></pre>
<p>My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well:</p>
<pre><code>def extendChoices(cList):
for i in range(0,9):
try:
if cList[i] is None:
cList[i] = "Choice %d"%(i+1)
except IndexError:
cList.append("Choice %d"%(i+1)
</code></pre>
<p>and</p>
<pre><code>def extendChoices(cList):
# Fill in any blank entries
for i, v in enumerate(cList):
cList[i] = v or "Choice %s" % (i+1)
# Extend the list to 9 choices
for j in range(len(cList)+1, 10):
cList.append("Choice %s" % (j))
</code></pre>
<p>I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.</p>
| 6
|
2009-02-05T14:11:32Z
| 516,491
|
<p>Unlike <code>zip</code>, Python's <code>map</code> automatically extends shorter sequences with <code>None</code>.</p>
<pre><code>map(lambda a, b: b if a is None else a,
choicesTxt,
['Choice %i' % n for n in range(1, 10)])
</code></pre>
<p>You could simplify the lambda to</p>
<pre><code>map(lambda a, b: a or b,
choicesTxt,
['Choice %i' % n for n in range(1, 10)])
</code></pre>
<p>if it's okay to treat other false-like objects in <code>choicesTxt</code> the same as <code>None</code>.</p>
| 8
|
2009-02-05T15:54:23Z
|
[
"python"
] |
Most pythonic way to extend a potentially incomplete list
| 516,039
|
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p>
<p>An example transformation would be</p>
<pre><code>['a','b',None,'c']
</code></pre>
<p>to</p>
<pre><code>['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']
</code></pre>
<p>My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well:</p>
<pre><code>def extendChoices(cList):
for i in range(0,9):
try:
if cList[i] is None:
cList[i] = "Choice %d"%(i+1)
except IndexError:
cList.append("Choice %d"%(i+1)
</code></pre>
<p>and</p>
<pre><code>def extendChoices(cList):
# Fill in any blank entries
for i, v in enumerate(cList):
cList[i] = v or "Choice %s" % (i+1)
# Extend the list to 9 choices
for j in range(len(cList)+1, 10):
cList.append("Choice %s" % (j))
</code></pre>
<p>I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.</p>
| 6
|
2009-02-05T14:11:32Z
| 516,554
|
<pre><code>def choice_n(index):
return "Choice %d" % (index + 1)
def add_choices(lst, length, default=choice_n):
"""
>>> add_choices(['a', 'b', None, 'c'], 9)
['a', 'b', 'Choice 3', 'c', 'Choice 5', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9']
"""
for i, v in enumerate(lst):
if v is None:
lst[i] = default(i)
for i in range(len(lst), length):
lst.append(default(i))
return lst
if __name__ == "__main__":
import doctest
doctest.testmod()
</code></pre>
| 1
|
2009-02-05T16:05:20Z
|
[
"python"
] |
Most pythonic way to extend a potentially incomplete list
| 516,039
|
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p>
<p>An example transformation would be</p>
<pre><code>['a','b',None,'c']
</code></pre>
<p>to</p>
<pre><code>['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']
</code></pre>
<p>My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well:</p>
<pre><code>def extendChoices(cList):
for i in range(0,9):
try:
if cList[i] is None:
cList[i] = "Choice %d"%(i+1)
except IndexError:
cList.append("Choice %d"%(i+1)
</code></pre>
<p>and</p>
<pre><code>def extendChoices(cList):
# Fill in any blank entries
for i, v in enumerate(cList):
cList[i] = v or "Choice %s" % (i+1)
# Extend the list to 9 choices
for j in range(len(cList)+1, 10):
cList.append("Choice %s" % (j))
</code></pre>
<p>I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.</p>
| 6
|
2009-02-05T14:11:32Z
| 516,671
|
<p>Simplest and most pythonic for me is:</p>
<pre><code>repl = lambda i: "Choice %d" % (i + 1) # DRY
print ([(x or repl(i)) for i, x in enumerate(aList)]
+ [repl(i) for i in xrange(len(aList), 9)])
</code></pre>
| 2
|
2009-02-05T16:30:29Z
|
[
"python"
] |
Most pythonic way to extend a potentially incomplete list
| 516,039
|
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p>
<p>An example transformation would be</p>
<pre><code>['a','b',None,'c']
</code></pre>
<p>to</p>
<pre><code>['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']
</code></pre>
<p>My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well:</p>
<pre><code>def extendChoices(cList):
for i in range(0,9):
try:
if cList[i] is None:
cList[i] = "Choice %d"%(i+1)
except IndexError:
cList.append("Choice %d"%(i+1)
</code></pre>
<p>and</p>
<pre><code>def extendChoices(cList):
# Fill in any blank entries
for i, v in enumerate(cList):
cList[i] = v or "Choice %s" % (i+1)
# Extend the list to 9 choices
for j in range(len(cList)+1, 10):
cList.append("Choice %s" % (j))
</code></pre>
<p>I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.</p>
| 6
|
2009-02-05T14:11:32Z
| 516,673
|
<p>Well in one line:</p>
<p><code><pre>[a or 'Choice %d' % i for a,i in map(None,["a","b",None,"c"],range(10))]</pre></code></p>
<p>Though that will replace anything that evaluates to False (e.g. None, '', 0 etc) with "Choice n". Best to replace the <code>"a or 'Choice %d' % i"</code> with a function if yuo don't want that.</p>
<p>The key thing is that <code>map</code> with an argument of None can be used to extend the list to the length needed with None in the required places.</p>
<p>A tidier (more pythonic) version would be:</p>
<p><code><pre>
def extend_choices(lst,length):
def replace_empty(value,index):
if value is None:
return 'Choice %d' % index
return value
return [replace_empty(value,index) for value,index in map(None,lst,range(length))]
</pre></code></p>
| 1
|
2009-02-05T16:30:53Z
|
[
"python"
] |
Most pythonic way to extend a potentially incomplete list
| 516,039
|
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p>
<p>An example transformation would be</p>
<pre><code>['a','b',None,'c']
</code></pre>
<p>to</p>
<pre><code>['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']
</code></pre>
<p>My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well:</p>
<pre><code>def extendChoices(cList):
for i in range(0,9):
try:
if cList[i] is None:
cList[i] = "Choice %d"%(i+1)
except IndexError:
cList.append("Choice %d"%(i+1)
</code></pre>
<p>and</p>
<pre><code>def extendChoices(cList):
# Fill in any blank entries
for i, v in enumerate(cList):
cList[i] = v or "Choice %s" % (i+1)
# Extend the list to 9 choices
for j in range(len(cList)+1, 10):
cList.append("Choice %s" % (j))
</code></pre>
<p>I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.</p>
| 6
|
2009-02-05T14:11:32Z
| 3,684,238
|
<p>My two cents...</p>
<pre><code>def extendchoices(clist):
clist.extend( [None]*(9-len(clist)) )
for i in xrange(9):
if clist[i] is None: clist[i] = "Choice %d"%(i+1)
</code></pre>
| 0
|
2010-09-10T11:28:39Z
|
[
"python"
] |
Most pythonic way to extend a potentially incomplete list
| 516,039
|
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p>
<p>An example transformation would be</p>
<pre><code>['a','b',None,'c']
</code></pre>
<p>to</p>
<pre><code>['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']
</code></pre>
<p>My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well:</p>
<pre><code>def extendChoices(cList):
for i in range(0,9):
try:
if cList[i] is None:
cList[i] = "Choice %d"%(i+1)
except IndexError:
cList.append("Choice %d"%(i+1)
</code></pre>
<p>and</p>
<pre><code>def extendChoices(cList):
# Fill in any blank entries
for i, v in enumerate(cList):
cList[i] = v or "Choice %s" % (i+1)
# Extend the list to 9 choices
for j in range(len(cList)+1, 10):
cList.append("Choice %s" % (j))
</code></pre>
<p>I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.</p>
| 6
|
2009-02-05T14:11:32Z
| 5,672,593
|
<p>If it's ok to replace any false value, eg '' or 0</p>
<pre><code>>>> mylist = ['a','b',None,'c']
>>> map(lambda a,b:a or "Choice %s"%b, mylist, range(1,10))
['a', 'b', 'Choice 3', 'c', 'Choice 5', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9']
</code></pre>
<p>If you really can only replace for None</p>
<pre><code>>>> map(lambda a,b:"Choice %s"%b if a is None else a, mylist, range(1,10))
['a', 'b', 'Choice 3', 'c', 'Choice 5', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9']
</code></pre>
| 0
|
2011-04-15T05:05:27Z
|
[
"python"
] |
Most pythonic way to extend a potentially incomplete list
| 516,039
|
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p>
<p>An example transformation would be</p>
<pre><code>['a','b',None,'c']
</code></pre>
<p>to</p>
<pre><code>['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9']
</code></pre>
<p>My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well:</p>
<pre><code>def extendChoices(cList):
for i in range(0,9):
try:
if cList[i] is None:
cList[i] = "Choice %d"%(i+1)
except IndexError:
cList.append("Choice %d"%(i+1)
</code></pre>
<p>and</p>
<pre><code>def extendChoices(cList):
# Fill in any blank entries
for i, v in enumerate(cList):
cList[i] = v or "Choice %s" % (i+1)
# Extend the list to 9 choices
for j in range(len(cList)+1, 10):
cList.append("Choice %s" % (j))
</code></pre>
<p>I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.</p>
| 6
|
2009-02-05T14:11:32Z
| 37,236,045
|
<pre><code>>>> my_list=['a','b',None,'c']
>>> map (lambda x,y:x or 'Choice {}'.format(y+1),my_list,range(9))
['a', 'b', 'Choice 3', 'c', 'Choice 5', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9']
</code></pre>
| 0
|
2016-05-15T08:25:44Z
|
[
"python"
] |
Is it possible to google search with the gdata API?
| 516,335
|
<p>I might be just thick (nothing new), but I can't seem to find anything related to an old-fashioned, vanilla google search in the gdata API docs. Anyone know if it's possible? (I know it probably is with a little tinkering, but I already have a Python web-scraping class created that does it for me, but I was wondering if using gdata would be the <em>right thing to do</em>)</p>
| 1
|
2009-02-05T15:22:28Z
| 516,400
|
<p>AFAIK, the gdata API is just for the Google Doc's application (Google Spreadsheet etc). </p>
<p>The search API does expose a REST interface for "Flash and other Non-Javascript Environments" though:</p>
<p><a href="http://code.google.com/apis/ajaxsearch/documentation/#fonje" rel="nofollow">http://code.google.com/apis/ajaxsearch/documentation/#fonje</a></p>
| 4
|
2009-02-05T15:35:12Z
|
[
"python",
"gdata-api"
] |
Python regex: Turn "ThisFileName.txt" into "This File Name.txt"
| 516,451
|
<p>I'm trying to add a space before every capital letter, except the first one.</p>
<p>Here's what I have so far, and the output I'm getting:</p>
<pre><code>>>> tex = "ThisFileName.txt"
>>> re.sub('[A-Z].', ' ', tex)
' his ile ame.txt'
</code></pre>
<p>I want:
'This File Name.txt'</p>
<p>(It'd be nice if I could also get rid of .txt, but I can do that in a separate operation.)</p>
| 2
|
2009-02-05T15:46:33Z
| 516,486
|
<p>Key concept here is backreferences in regular expressions:</p>
<pre><code>import re
text = "ThisFileName.txt"
print re.sub('([a-z])([A-Z])', r'\1 \2', text)
# Prints: "This File Name.txt"
</code></pre>
<p>For pulling off the '.txt' in a reliable way, I recommend <code>os.path.splitext()</code></p>
<pre><code>import os
filename = "ThisFileName.txt"
print os.path.splitext(filename)
# Prints: ('ThisFileName', '.txt')
</code></pre>
| 9
|
2009-02-05T15:53:24Z
|
[
"python",
"regex"
] |
Python regex: Turn "ThisFileName.txt" into "This File Name.txt"
| 516,451
|
<p>I'm trying to add a space before every capital letter, except the first one.</p>
<p>Here's what I have so far, and the output I'm getting:</p>
<pre><code>>>> tex = "ThisFileName.txt"
>>> re.sub('[A-Z].', ' ', tex)
' his ile ame.txt'
</code></pre>
<p>I want:
'This File Name.txt'</p>
<p>(It'd be nice if I could also get rid of .txt, but I can do that in a separate operation.)</p>
| 2
|
2009-02-05T15:46:33Z
| 516,495
|
<pre><code>re.sub('([a-z])([A-Z])', '\\1 \\2', 'TheFileName.txt')
</code></pre>
<p>EDIT: StackOverflow eats some \s, when not in 'code mode'... Because I forgot to add a newline after the code above, it was not interpreted in 'code mode' :-((. Since I added that text here I didn't have to change anything and it's correct now.</p>
| 2
|
2009-02-05T15:55:08Z
|
[
"python",
"regex"
] |
Python regex: Turn "ThisFileName.txt" into "This File Name.txt"
| 516,451
|
<p>I'm trying to add a space before every capital letter, except the first one.</p>
<p>Here's what I have so far, and the output I'm getting:</p>
<pre><code>>>> tex = "ThisFileName.txt"
>>> re.sub('[A-Z].', ' ', tex)
' his ile ame.txt'
</code></pre>
<p>I want:
'This File Name.txt'</p>
<p>(It'd be nice if I could also get rid of .txt, but I can do that in a separate operation.)</p>
| 2
|
2009-02-05T15:46:33Z
| 516,533
|
<p>Another possible regular expression using a look behind:</p>
<pre><code>(?<!^)([A-Z])
</code></pre>
| 2
|
2009-02-05T16:01:31Z
|
[
"python",
"regex"
] |
Python regex: Turn "ThisFileName.txt" into "This File Name.txt"
| 516,451
|
<p>I'm trying to add a space before every capital letter, except the first one.</p>
<p>Here's what I have so far, and the output I'm getting:</p>
<pre><code>>>> tex = "ThisFileName.txt"
>>> re.sub('[A-Z].', ' ', tex)
' his ile ame.txt'
</code></pre>
<p>I want:
'This File Name.txt'</p>
<p>(It'd be nice if I could also get rid of .txt, but I can do that in a separate operation.)</p>
| 2
|
2009-02-05T15:46:33Z
| 518,338
|
<p>It is not clear what you want to do if the filename is <code>Hello123There.txt</code>. So, if you want a space before all capital letters regardless of what precedes them, you can:</p>
<pre><code>import re
def add_space_before_caps(text):
"Add a space before all caps except at start of text"
return re.sub(r"(?<!^)(?=[A-Z])", " ", text)
>>> add_space_before_caps("Hello123ThereIBM.txt")
'Hello123 There I B M.txt'
</code></pre>
| 1
|
2009-02-05T22:49:01Z
|
[
"python",
"regex"
] |
Is there a Vim equivalent to the Linux/Unix "fold" command?
| 516,501
|
<p>I realize there's a way in Vim to hide/fold lines, but what I'm looking for is a way to select a block of text and have Vim wrap lines at or near column 80. </p>
<p>Mostly I want to use this on comments in situations where I'm adding some text to an existing comment that pushes it over 80 characters. It would also be nice if it could insert the comment marker at the beginning of the line when it wraps too. Also I'd prefer the solution to not autowrap the entire file since I have a particular convention that I use when it comes to keeping my structured code under the 80 character line-length. </p>
<p>This is mostly for Python code, but I'm also interested in learning the general solution to the problem in case I have to apply it to other types of text.</p>
| 6
|
2009-02-05T15:56:00Z
| 516,536
|
<pre><code>gq
</code></pre>
<p>It's controlled by the textwidth option, see <code>":help gq"</code> for more info. </p>
<p><code>gq</code> will work on the current line by default, but you can highlight a visual block with <kbd>Ctrl</kbd>+<kbd>V</kbd> and format multiple lines / paragraphs like that.</p>
<p><code>gqap</code> does the current "paragraph" of text.</p>
| 11
|
2009-02-05T16:02:09Z
|
[
"python",
"vim",
"formatting",
"comments",
"textwrapping"
] |
Is there a Vim equivalent to the Linux/Unix "fold" command?
| 516,501
|
<p>I realize there's a way in Vim to hide/fold lines, but what I'm looking for is a way to select a block of text and have Vim wrap lines at or near column 80. </p>
<p>Mostly I want to use this on comments in situations where I'm adding some text to an existing comment that pushes it over 80 characters. It would also be nice if it could insert the comment marker at the beginning of the line when it wraps too. Also I'd prefer the solution to not autowrap the entire file since I have a particular convention that I use when it comes to keeping my structured code under the 80 character line-length. </p>
<p>This is mostly for Python code, but I'm also interested in learning the general solution to the problem in case I have to apply it to other types of text.</p>
| 6
|
2009-02-05T15:56:00Z
| 520,076
|
<p>Take a look at ":help =" and ":help 'equalprg"</p>
<pre><code>:set equalprg=fold
</code></pre>
<p>and in normal mode == filters the current line through the external fold program. Or visual-select something and hit =</p>
| 0
|
2009-02-06T12:12:52Z
|
[
"python",
"vim",
"formatting",
"comments",
"textwrapping"
] |
Mixed language source directory layout
| 516,798
|
<p>We are running a large project with several different languages: Java, Python, PHP, SQL and Perl. </p>
<p>Until now people have been working in their own private repositories, but now we want to merge the entire project in a single repository. The question now is: how should the directory structure look? Should we have separate directories for each language, or should we separate it by component/project? How well does python/perl/java cope with a common directory layout?</p>
| 5
|
2009-02-05T16:57:15Z
| 516,827
|
<p>My experience indicates that this kind of layout is best:</p>
<pre><code>mylib/
src/
java/
python/
perl/
.../
bin/
java/
python/
perl/
stage/
dist/
</code></pre>
<p><code>src</code> is your source, and is the only thing checked in.</p>
<p><code>bin</code> is where "compilation" occurs to during the build, and is not checked in.</p>
<p><code>stage</code> is where you copy things during the build to prepare them for packaging</p>
<p><code>dist</code> is where you put the build artifacts</p>
<p>I put the module/component/library at the top of the hierarchy, because I build every module separately, and use a dependency manager to combine them as needed.</p>
<p>Of course, naming conventions vary. But I've found this to work quite satisfactorily.</p>
| 6
|
2009-02-05T17:01:47Z
|
[
"java",
"python",
"sql",
"directory"
] |
Mixed language source directory layout
| 516,798
|
<p>We are running a large project with several different languages: Java, Python, PHP, SQL and Perl. </p>
<p>Until now people have been working in their own private repositories, but now we want to merge the entire project in a single repository. The question now is: how should the directory structure look? Should we have separate directories for each language, or should we separate it by component/project? How well does python/perl/java cope with a common directory layout?</p>
| 5
|
2009-02-05T16:57:15Z
| 518,493
|
<p>I think the best thing to do would be to ensure that your various modules don't depend upon being in the same directory (i.e. separate by component). A lot of people seem to be deathly afraid of this idea, but a good set of build scripts should be able to automate away any pain.</p>
<p>The end goal would be to make it easy to install the infrastructure, and then really easy to work on a single component once the environment is setup.</p>
<p>(It's important to note that I come from the Perl and CL worlds, where we install "modules" into some global location, like ~/perl or ~/.sbcl, rather than including each module with each project, like Java people do. You'd think this would be a maintenance problem, but it ends up not being one. With a script that updates each module from your git repository (or CPAN) on a regular basis, it is really the best way.)</p>
<p>Edit: one more thing:</p>
<p>Projects always have external dependencies. My projects need Postgres and a working Linux install. It would be insane to bundle this with the app code in version control -- but a script to get everything setup on a fresh workstation is very helpful. </p>
<p>I guess what I'm trying to say, in a roundabout way perhaps, is that I don't think you should treat your internal modules differently from external modules.</p>
| 2
|
2009-02-05T23:37:25Z
|
[
"java",
"python",
"sql",
"directory"
] |
Is plotting an image on a map with matplotlib possible?
| 516,935
|
<p>Using basemap it's easy to plot a set of coordinates, like so:</p>
<pre><code>x, y = m(lons, lats)
m.plot(x, y, 'go')
</code></pre>
<p>but would it be possible to use an image instead of the green circle ('go')? I didn't find a direct way of doing this from the documentation.</p>
<p>So, let's clarify this a bit: I'm using a map generated with basemap as a background and would like to plot some .png images on top of it instead of the regular plain markers.</p>
| 8
|
2009-02-05T17:28:10Z
| 517,320
|
<p>If you want to draw <code>.png</code> images then you should try <a href="http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.imshow">http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.imshow</a></p>
<p>You might also be interested in the Matplotlib Basemap toolkit. <a href="http://matplotlib.sourceforge.net/basemap/doc/html/">http://matplotlib.sourceforge.net/basemap/doc/html/</a></p>
| 6
|
2009-02-05T18:47:00Z
|
[
"python",
"matplotlib"
] |
Is plotting an image on a map with matplotlib possible?
| 516,935
|
<p>Using basemap it's easy to plot a set of coordinates, like so:</p>
<pre><code>x, y = m(lons, lats)
m.plot(x, y, 'go')
</code></pre>
<p>but would it be possible to use an image instead of the green circle ('go')? I didn't find a direct way of doing this from the documentation.</p>
<p>So, let's clarify this a bit: I'm using a map generated with basemap as a background and would like to plot some .png images on top of it instead of the regular plain markers.</p>
| 8
|
2009-02-05T17:28:10Z
| 11,548,194
|
<p>For your reference, I answered a similar question to this the other day: <a href="http://stackoverflow.com/questions/11487797/python-matplotlib-basemap-overlay-small-image-on-map-plot/11495585#11495585">Python Matplotlib Basemap overlay small image on map plot</a></p>
| 1
|
2012-07-18T18:41:53Z
|
[
"python",
"matplotlib"
] |
Control 2 separate Excel instances by COM independently... can it be done?
| 516,946
|
<p>I've got a legacy application which is implemented in a number of Excel workbooks. It's not something that I have the authority to re-implement, however another application that I do maintain does need to be able to call functions in the Excel workbook. </p>
<p>It's been given a python interface using the Win32Com library. Other processes can call functions in my python package which in turn invokes the functions I need via Win32Com.</p>
<p>Unfortunately COM does not allow me to specify a particular COM process, so at the moment no matter how powerful my server I can only control one instance of Excel at a time on the computer. If I were to try to run more than one instance of excel there would be no way of ensuring that the python layer is bound to a specific Excel instance. </p>
<p>I'd like to be able to run more than 1 of my excel applications on my Windows server concurrently. Is there a way to do this? For example, could I compartmentalize my environment so that I could run as many Excel _ Python combinations as my application will support?</p>
| 5
|
2009-02-05T17:32:22Z
| 516,983
|
<p>If you application uses a single excel file which contains macros which you call, I fear the answer is probably no since aside from COM Excel does not allow the same file to be opened with the same name (even if in different directories). You may be able to get around this by dynamically copying the file to another name before opening. </p>
<p>My python knowledge isn't huge, but in most languages there is a way of specifying when you create a COM object whether you wish it to be a new object or connect to a preexisting instance by default. Check the python docs for something along these lines.</p>
<p>Can you list the kind of specific problems you are having and exactly what you are hoping to do?</p>
| 0
|
2009-02-05T17:42:57Z
|
[
"python",
"windows",
"excel",
"com"
] |
Control 2 separate Excel instances by COM independently... can it be done?
| 516,946
|
<p>I've got a legacy application which is implemented in a number of Excel workbooks. It's not something that I have the authority to re-implement, however another application that I do maintain does need to be able to call functions in the Excel workbook. </p>
<p>It's been given a python interface using the Win32Com library. Other processes can call functions in my python package which in turn invokes the functions I need via Win32Com.</p>
<p>Unfortunately COM does not allow me to specify a particular COM process, so at the moment no matter how powerful my server I can only control one instance of Excel at a time on the computer. If I were to try to run more than one instance of excel there would be no way of ensuring that the python layer is bound to a specific Excel instance. </p>
<p>I'd like to be able to run more than 1 of my excel applications on my Windows server concurrently. Is there a way to do this? For example, could I compartmentalize my environment so that I could run as many Excel _ Python combinations as my application will support?</p>
| 5
|
2009-02-05T17:32:22Z
| 517,975
|
<p>I don't know a thing about Python, unfortunately, but if it works through COM, Excel is not a Single-Instance application, so you should be able to create as many instances of Excel as memory permits.</p>
<p>Using C# you can create multiple Excel Application instances via:</p>
<pre><code>Excel.Application xlApp1 = new Excel.Application();
Excel.Application xlApp2 = new Excel.Application();
Excel.Application xlApp3 = new Excel.Application();
</code></pre>
<p>Using late binding in C# you can use:</p>
<pre><code>object objXL1 = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));
object objXL2 = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));
object objXL3 = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));
</code></pre>
<p>If using VB.NET, VB6 or VBA you can use CreateObject as follows:</p>
<pre><code>Dim objXL1 As Object = CreateObject("Excel.Application")
Dim objXL2 As Object = CreateObject("Excel.Application")
Dim objXL3 As Object = CreateObject("Excel.Application")
</code></pre>
<p>Unfortunately, in Python, I don't have a clue. But unless there is some limitation to Python (which I can't imagine?) then I would think that it's very do-able.</p>
<p>That said, the idea of having multiple instances of Excel acting as some kind of server for other operations sounds pretty dicy... I'd be careful to test what you are doing, especially with respect to how many instances you can have open at once without running out of memory and what happens to the calling program if Excel crashed for some reason.</p>
| 2
|
2009-02-05T21:19:34Z
|
[
"python",
"windows",
"excel",
"com"
] |
Control 2 separate Excel instances by COM independently... can it be done?
| 516,946
|
<p>I've got a legacy application which is implemented in a number of Excel workbooks. It's not something that I have the authority to re-implement, however another application that I do maintain does need to be able to call functions in the Excel workbook. </p>
<p>It's been given a python interface using the Win32Com library. Other processes can call functions in my python package which in turn invokes the functions I need via Win32Com.</p>
<p>Unfortunately COM does not allow me to specify a particular COM process, so at the moment no matter how powerful my server I can only control one instance of Excel at a time on the computer. If I were to try to run more than one instance of excel there would be no way of ensuring that the python layer is bound to a specific Excel instance. </p>
<p>I'd like to be able to run more than 1 of my excel applications on my Windows server concurrently. Is there a way to do this? For example, could I compartmentalize my environment so that I could run as many Excel _ Python combinations as my application will support?</p>
| 5
|
2009-02-05T17:32:22Z
| 2,263,641
|
<p>See <a href="http://timgolden.me.uk/python/win32_how_do_i/start-a-new-com-instance.html" rel="nofollow">"Starting a new instance of a COM application" by Tim Golden</a>, also referenced <a href="http://www.thalesians.com/finance/index.php/Knowledge_Base/Python/General#Starting_a_new_instance_of_a_COM_application" rel="nofollow">here</a>, which give the hint to use</p>
<pre><code>xl_app = DispatchEx("Excel.Application")
</code></pre>
<p>rather than</p>
<pre><code>xl_app = Dispatch("Excel.Application")
</code></pre>
<p>to start a separate process. So you should be able to do:</p>
<pre><code>xl_app_1 = DispatchEx("Excel.Application")
xl_app_2 = DispatchEx("Excel.Application")
xl_app_3 = DispatchEx("Excel.Application")
</code></pre>
<p><strong>Note</strong> that when you're done, to close the app, I've found it's necessary to do:</p>
<pre><code>xl_app.Quit()
xl_app = None
</code></pre>
<p>I found the process won't shut down until <code>xl_app = None</code>, that is, the Python COM object's reference count goes to zero.</p>
<p><strong>Note</strong> I'm having one remaining problem: while my Python program is running, if I double-click an Excel file in Explorer (at least, on Win2k), it ends up opening the file in the existing Excel process that Python started (which is running hidden), which disrupts the Python program. I haven't yet found a resolution for this.</p>
| 4
|
2010-02-15T01:53:25Z
|
[
"python",
"windows",
"excel",
"com"
] |
return eats exception
| 517,060
|
<p>I found the following behavior at least <em>weird</em>:</p>
<pre><code>def errors():
try:
ErrorErrorError
finally:
return 10
print errors()
# prints: 10
# It should raise: NameError: name 'ErrorErrorError' is not defined
</code></pre>
<p>The exception disappears when you use <code>return</code> inside a <code>finally</code> clause. Is that a bug? Is that documented anywhere?</p>
<p>But the real question (and the answer I will mark as correct) is:<br>
What is the python developers' reason to allow that odd behavior?</p>
| 13
|
2009-02-05T17:59:35Z
| 517,080
|
<p>Returning from a finally is <strong>not</strong> a good idea. I know C# specifically forbids doing this.</p>
| 4
|
2009-02-05T18:03:11Z
|
[
"python",
"exception",
"return",
"finally"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.