Skip to content

Tag: python

Python: Write a list of tuples to a file

How can I write the following list: to a text file with two columns (8 rfa) and many rows, so that I have something like this: Answer If you want to use str.format(), replace 2nd line with:

Proper way to test Django signals

I’m trying to test sent signal and it’s providing_args. Signal triggered inside contact_question_create view just after form submission. My TestCase is something like: Is this the proper way to test this signal? Any better ideas? Answer I’ve resolved the problem by myself. I think that the b…

in numpy what is the multi dimensional equivalent of take

I have this bit of code Where blocks is a 3 dimensional numpy array. What I’d like to do is replace the list comprehension with something like numpy.take, however take seems to only deal with single dimension indices. Is there something like take that will work with multidimensional indices? Also I know…

Change working directory in shell with a python script

I want to implement a userland command that will take one of its arguments (path) and change the directory to that dir. After the program completion I would like the shell to be in that directory. So I want to implement cd command, but with external program. Can it be done in a python script or I have to writ…

Python: Sum string lengths

Is there a more idiomatic way to sum string lengths in Python than by using a loop? I tried sum(), but it only works for integers: Answer I know this is an old question, but I can’t help noting that the Python error message tells you how to do this: So:

How to strip all whitespace from string

How do I strip all the spaces in a python string? For example, I want a string like strip my spaces to be turned into stripmyspaces, but I cannot seem to accomplish that with strip(): Answer Taking advantage of str.split’s behavior with no sep parameter: If you just want to remove spaces instead of all …

Titlecasing a string with exceptions

Is there a standard way in Python to titlecase a string (i.e. words start with uppercase characters, all remaining cased characters have lowercase) but leaving articles like and, in, and of lowercased? Answer There are a few problems with this. If you use split and join, some white space characters will be ig…

How to get the text cursor position in Windows?

Is it possible to get the overall cursor position in Windows using the standard Python libraries? Answer This retrieves the cursor’s position, in screen coordinates – point = (x,y) Retrieves information about the global cursor. Links: http://msdn.microsoft.com/en-us/library/ms648389(VS.85).aspx ht…