best way to do some simple tasks
exarkun at intarweb.us
Thu Jan 30 00:46:31 CET 2003
On Wed, Jan 29, 2003 at 03:31:59PM -0800, Erik Lechak wrote:
> Hello all,
> I am transitioning from perl to python. I find myself trying to do
> many things in a perlish way. Perl made many common tasks such as
> string manipulations easy (in a perlish sort of way). So I was
> wondering if someone could suggest the "pythonish" way of doing these
> things. I have read tons of documentation and can do all of the
> following tasks, but my code does not look "professional".
> 1) String interpolation of lists and dictionaries
> What is the correct and best way to do this?
> x =[1,2,3,4]
> print "%(x)i blah" % vars() # <- does not work
There have been many proposals regarding this. Suffice it to say none
have yet made it into the language.
> 2) Perform a method on each element of an array
> a= [" hello ", " there "]
> how do I use the string's strip() method on each element of the
a = [x.strip() for x in a]
a = map(str.strip, a)
> 3) What is the best way to do this?
> how do I get c=a+b (c=[2,3,4])?
c = map(operator.add, a, b)
> 4) Why does this work this way?
> for h in d:
> print d
> >>>[1, 2, 3, 4, 5]
> Is there a python reason why h is a copy not a reference to the
> element in the list?
h -is- a reference to the element in the list. However, ints are
immutable. h += 1 above is the same as "h = h + 1", which rebinds h to a
new int object. If you want to change the elements of the list, iterate
over the indices of the list, like so:
d = range(5)
for h in range(len(d)):
d[h] = d[h] + 1
(soapbox) More generally, avoid using +=. It leads to just this sort of
confusion - Is it mutating the object in place, or rebind the variable to a
new object? It's often very difficult to tell. Stick to the long form for
immutable objects, and use methods for mutable ones (.append() for lists,
| 8 lines
| (So sue me)
up 45 days, 3:49, 3 users, load average: 0.00, 0.07, 0.11
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Size: 196 bytes
Desc: not available
More information about the Python-list