Is there a way to subtract 3 from every digit of a number?

Chris Angelico rosuav at gmail.com
Sat Feb 20 23:57:59 EST 2021


On Sun, Feb 21, 2021 at 3:50 PM Dan Stromberg <drsalists at gmail.com> wrote:
>
> On Sat, Feb 20, 2021 at 7:13 PM Ming <ming at pgp.cool> wrote:
>
> > I just wrote a very short code can fulfill your needs:
> >
> > a = 2342
> > b = int("".join(map(lambda x: str((int(x)-3)%10) ,list(str(a)))))
> >
> I tend to favor plenty of temporary variables with descriptive names, but
> this is indeed short.
>
> Apart from that, you may find that using a generator expression is shorter
> and clearer than map+lambda.  It should allow to additionally eliminate the
> list conversion.

For what it's worth, map doesn't require list conversion either - it's
perfectly happy (as are most things in Python) to iterate over a
string.

ChrisA


More information about the Python-list mailing list