C-like assignment expression?

2008-05-21 Thread boblatest
Hello,

I have an if-elif chain in which I'd like to match a string against
several regular expressions. Also I'd like to use the match groups
within the respective elif... block. The C-like idiom that I would
like to use is this:

if (match = my_re1.match(line):
  # use match
elsif (match = my_re2.match(line)):
  # use match
elsif (match = my_re3.match(line))
  # use match

...buy this is illegal in python. The other way is to open up an else:
block in each level, do the assignment and then the test. This
unneccessarily leads to deeper and deeper nesting levels which I find
ugly. Just as ugly as first testing against the RE in the elif: clause
and then, if it matches, to re-evaluate the RE to access the match
groups.

Thanks,
robert
--
http://mail.python.org/mailman/listinfo/python-list


Filling in a tuple from unknown size list

2009-11-27 Thread boblatest
Hello all,

(sorry for posting from Google. I currently don't have access to my
normal nntp account.)

Here's my question: Given a list of onknown length, I'd like to be
able to do the following:

(a, b, c, d, e, f) = list

If the list has fewer items than the tuple, I'd like the remaining
tuple elements to be set to "None". If the list is longer, I'd like
the excess elements to be ignored.

The code snippet below does what I want, I was just wondering if there
was an interesting "Pythonic" way of expressing the same thing.

Thanks,
robert

def iter_inf(li, n):
for i in range(n):
if i < len(li):
r = li[i]
else:
r = None
i += 1
yield r


li = ['a', 'b', 'c']
(a, b, c, d, e) =  iter_inf(li, 5)
print a, b, c, d, e
-- 
http://mail.python.org/mailman/listinfo/python-list


Create a backslash-escaped version of a string?

2010-02-08 Thread boblatest
Hello,

I'd like to have control characters in a string to be converted to
their backslash-escaped counterparts. I looked in the encoders section
of the string module but couldn't find anything appropriate. I could
write it myself but I'm sure something of the sort exists. The
hypothetical method "c_escaped()" would work like this:

>>> a="abc\rdef"
>>> print a.c_escaped()
abc\rdef
>>>

Thanks,
robert
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Create a backslash-escaped version of a string?

2010-02-08 Thread boblatest
On Feb 8, 12:28 pm, Chris Rebert  wrote:
> print a.encode("string-escape")

How could I miss that? I was on that doc page already. Should have
typed "/escape" in the browser ;-)

Thanks,
robert
-- 
http://mail.python.org/mailman/listinfo/python-list