pythonic

String separation in required format, Pythonic way? (with or w/o Regex)

I have a string in the format: t='@abc @def Hello this part is text' I want to get this: l=["abc", "def"] s='Hello this part is text' I did this: a=t[t.find(' ',t.rfind('@')):].strip() s=t[:t.find(' ',t.rfind('@'))].strip() b=a.split('@') l=[i.strip() for i in b][1:] It works for the most part, but it fails when the text part h...

Python: Am I missing something?

I'm in the process of learning Python while implementing build scripts and such. And for the moment everything is working fine in that the scripts do what they need to do. But I keep having the feeling I'm missing something, such as "The Python Way". I know build scripts and glue scripts are not really the most exciting development work ...

What are the important language features (idioms) of Python to learn early on

I would be interested in knowing what the StackOverflow community thinks are the important language features (idioms) of Python. Features that would define a programmer as Pythonic. Python (pythonic) idiom - "code expression" that is natural or characteristic to the language Python. Plus, Which idioms should all Python programmers lea...

Python program to find fibonacci series. More Pythonic way.

There is another thread to discuss Fibo series in Python. This is to tweak code into more pythonic. How to write the Fibonacci Sequence in Python I am in love with this program I wrote to solve Project Euler Q2. I am newly coding in Python and rejoice each time I do it The Pythonic way! Can you suggest a better Pythonic way to do this? ...

"Pythonic" equivalent for handling switch and multiple string compares

Alright, so my title sucked. An example works better: input = 'check yahoo.com' I want to parse input, using the first word as the "command", and the rest of the string as a parameter. Here's the simple version of how my non-Pythonic mind is coding it: if len(input) > 0: a = input.split(' ') if a[0] == 'check': if l...

Iterability in Python

I am trying to understand Iterability in Python. As I understand, __iter__() should return an object that has next() method defined which must return a value or raise StopIteration exception. Thus I wrote this class which satisfies both these conditions. But it doesnt seem to work. What is wrong? class Iterator: def __init__(self)...

Check if value exists in nested lists

in my list: animals = [ ['dog', ['bite'] ], ['cat', ['bite', 'scratch'] ], ['bird', ['peck', 'bite'] ], ] add('bird', 'peck') add('bird', 'screech') add('turtle', 'hide') The add function should check that the animal and action haven't been added before adding them to the list. Is there a way to accomplish...

What is a clean, pythonic way to have multiple constructors in Python?

I can't find a definitive answer for this. AFAIK, you can't have multiple __init__ functions in a Python class. So what is a good way to solve this problem? Suppose I have an class called Cheese with the number_of_holes property. How can I have two ways of creating cheese-objects... one that takes a number of holes like this: parmesa...

Pythonic ways to use 'else' in a for loop

I have hardly ever noticed a python program that uses else in a for loop. I recently used it to perform an action based on the loop variable condition while exiting; as it is in the scope. What is the pythonic way to use an else in a for loop? Are there any notable use cases? And, yea. I dislike using break statement. I'd rather set t...

What's a more elegant rephrasing of this cropping algorithm? (in Python)

I want to crop a thumbnail image in my Django application, so that I get a quadratic image that shows the center of the image. This is not very hard, I agree. I have already written some code that does exactly this, but somehow it lacks a certain ... elegance. I don't want to play code golf, but there must be a way to express this shor...

HTTP Authentication in Python

Whats is the python urllib equivallent of curl -u username:password status="abcd" http://example.com/update.json I did this: handle = urllib2.Request(url) authheader = "Basic %s" % base64.encodestring('%s:%s' % (username, password)) handle.add_header("Authorization", authheader) Is there a better / simpler way? ...

Is there a more pythonic way to build this dictionary?

What is the "most pythonic" way to build a dictionary where I have the values in a sequence and each key will be a function of its value? I'm currently using the following, but I feel like I'm just missing a cleaner way. NOTE: values is a list that is not related to any dictionary. for value in values: new_dict[key_from_value(value)...

Iterate over a python sequence in multiples of n?

How do I process the elements of a sequence in batches, idiomatically? For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following: for x, y in "abcdef": print "%s%s\n" % (x, y) ab cd ef Of course, this doesn't work because it is expecting a single element from the list which its...

Implementing a 'function-calling function'

I would like to write a bit of code that calls a function specified by a given argument. EG: def caller(func): return func() However what I would also like to do is specify optional arguments to the 'caller' function so that 'caller' calls 'func' with the arguments specified (if any). def caller(func, args): # calls func with th...

What HTTP framework to use for simple but scalable app?

What HTTP framework should I use for a simple application with implied scalability, priferable Pythonic? I would like to be able to smoothly add new features to my app when it has already been deployed. ...

How to designate unreachable python code

What's the pythonic way to designate unreachable code in python as in: gender = readFromDB(...) # either 'm' or 'f' if gender == 'm': greeting = 'Mr.' elif gender == 'f': greeting = 'Ms.' else: # What should this line say? ...

What are some good ways to set a path in a Multi-OS supported Python script

When writing a Python script that can be executed in different operating system environments (Windows/*nix), what are some good ways to set a path? In the example below I would like to have the logfiles stored in the logs folder under the current directory. Is this an acceptable approach (I'm rather new to Python) or are there better way...

list.append or list += ?

Which is more pythonic? list.append(1) or list += [1] ...

Can a Python module use the imports from another file?

I have something like this: # a.py import os class A: ... # b.py import a class B(A): ... In class B (b.py) I'd like to be able to use the modules imported in a.py (os in this case). Is it possible to achieve this behavior in Python or should I import the modules in both files? Edit: I'm not worried about the import ti...

Pythonic way to split comma separated numbers into pairs

I'd like to split a comma separated value into pairs: >>> s = '0,1,2,3,4,5,6,7,8,9' >>> pairs = # something pythonic >>> pairs [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] What would # something pythonic look like? How would you detect and handle a string with an odd set of numbers? ...