Alex Freeland
Alex Freeland

Reputation: 11

Multiple List Comprehensions in One Line - Python

This is more of a curiosity/ efficiency question. I am replacing all numbers in a string with x+1, and if its a 9 changing to a 0. My broken code:

def add_one(string):
   return ''.join([(str(int(x)+1) for x in string if x in "012345678") and (y for y in string if y != '9') and (0 for z in string if z == '9')])

The goal is that "123abc99" would result in "234abc00".

The code is doable over multiple lines, but is multiple list comprehensions in one line possible?

Upvotes: 1

Views: 266

Answers (1)

zondo
zondo

Reputation: 20366

return "".join(str((int(x)+1) % 10) if x.isdigit() else x for x in string)

Upvotes: 1

Related Questions