turn list of letters into an array of integers

Terry Reedy tjreedy at udel.edu
Wed Oct 24 11:56:19 EDT 2012


On 10/24/2012 1:23 AM, seektime wrote:
> Here's some example code. The input is a list which is a "matrix" of letters:
>     a  b  a
>     b  b  a
>
> and I'd like to turn this into a Python array:
>
>    1 2 1
>    2 2 1
>
> so 1 replaces a, and 2 replaces b.

If you are going to replace single characters (letters) with single 
characters (digits), use maketrans and translate.

 >>> 'a b c'.translate(str.maketrans('abc', '123'))
'1 2 3'

-- 
Terry Jan Reedy




More information about the Python-list mailing list