Equivalents of Ruby's "!" methods?

Ben Finney bignose+hates-spam at benfinney.id.au
Mon Aug 25 09:08:38 EDT 2008


"Simon Mullis" <simon at mullis.co.uk> writes:

> Consider the following hash:
> 
> h = { "1" : "a\r", "2" : "b\n" }

This is a 'dict' instance in Python. A 'hash' is a different concept.

> In order to strip the dict values in Python I (think) I can only do
> something like:
> 
> for k,v in h.items:
>     h[k] = v.strip()

The above won't do what you describe, since 'h.items' evaluates to
that function object, which is not iterable. If you want the return
value of the function, you must call the function:

    for (k, v) in h.items():
        h[k] = v.strip()

This will create a new value from each existing value, and re-bind
each key to the new value for that key. Clear, straightforward, and
Pythonic.

You can also create a new dict from a generator, and re-bind the name
to that new dict:

    h = dict(
        (k, v.strip())
        for (k, v) in h.items())

Also quite Pythonic, but rather less clear if one hasn't yet
understood generator expressions. Very useful to have when needed,
though.

> While in Ruby - for the equivale dict/hash - I have the option of an
> in-place method:
> 
> h.each_value { |v| val.strip! }
> 
> Are there Python equivalents to the "!" methods in Ruby?

I'm not overly familiar with Ruby, but the feature you describe above
seems to rely on mutating the string value in-place. Is that right?

Strings in Python are immutable (among other reasons, this allows them
to meet the requirement of dict keys to be immutable, which in turn
allows dict implementations to be very fast), so you can only get a
new value for a string by creating a new string instance and re-bind
the reference to that new value.

Either of the above Python implementations will do this.

-- 
 \           “Kissing a smoker is like licking an ashtray.” —anonymous |
  `\                                                                   |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list