accessing elements in multi-dimensional sequences

Matteo Dell'Amico della at toglimi.linux.it
Fri May 28 06:34:15 EDT 2004


Rodrigo Daunaravicius wrote:
> Is there an elegant way to directly refer the 2nd dimension of a
> multi-dimensional sequence (like the nth character in a list of strings).
> An example would be deleting the newline in all the strings from a list
> obtained through readlines without recurring to 'for' loops.
> I would expect this to work:
> 
> 
>>>>d
> 
> ['0891931243\n', '0325443777\n', '0933477028\n', '0699624617\n',
> '0922210996\n']
> 
>>>>del d[:][-1]
>>>>d
> 
> ['0891931243', '0325443777', '0933477028', '0699624617', '0922210996']
> 
> But it doesn't, d remains unchanged.
> 
> Another attempt produced what seemed to me like a counter-intuitive result
> 
> 
>>>>b=d[:][:-1]
>>>>b
> 
> ['0891931243\n', '0325443777\n', '0933477028\n', '0699624617\n']
> 
> 
> Regards from a python newbie,
> Rodrigo Daunarovicius

You can express that as [s[:-1] for s in d].
Besides, strings are immutable: if s is a string, you can't do something 
like s[3] = 'a': though, you can create a new object and tell s to refer 
to it: s = s[:3] + 'a' + s[4:]

If all you want to do is remove trailing whitespace, have also a look at 
the string strip, lstrip and rstrip methods.

-- 
Ciao,
Matteo



More information about the Python-list mailing list