ucei
ucei

Reputation: 51

How to make this line shorter

I'm writing this in python, long version:

file_name = data.decode().splitlines()[0].split(" ")[1]
if file_name = '/'
    file_name = '/index.html'

I would like to make this whole block just one line. I wrote:

file_name = data.decode().splitlines()[0].split(" ")[1] if data.decode().splitlines()[0].split(" ")[1] != '/' else '/index.html'

But of course, it's too long. Is there a way I could still fit this in one line for less than 120 char?

Upvotes: 0

Views: 80

Answers (1)

go2nirvana
go2nirvana

Reputation: 1638

There is no need, though. Your one liner makes all computations twice and also quite hard to grasp, wheres multiline variant clearly shows the intent and is easy to understand.

However, for python3.8+ you could use walrus operator:

file_name = name if (name := data.decode().splitlines()[0].split(" ")[1]) != '/' else '/index.html'

If that is not an option. Just break the line:

file_name = (data.decode().splitlines()[0].split(" ")[1] 
             if data.decode().splitlines()[0].split(" ")[1] != '/'
             else '/index.html')

Upvotes: 4

Related Questions