Question

I was rewritting some legacy code, when I stumbled into the following:

rounded_val = (len(src_string) / 2) * 2

This takes advantage of integer division behavior, to round the length value of the string, if odd, to the first even value before it. But integer division is about to change on Python 3, and I need to change this line.

What is the optimal way to do this?

Was it helpful?

Solution 3

How about this:

rounded_val = len(src_string) & (-2)

Although it is sometimes not obvious to someone not familiar with binary arithmetic.

OTHER TIPS

Use // floor division instead if you don't like relying on the Python 2 / behaviour for integer operands:

rounded_val = (len(src_string) // 2) * 2

Maybe

rounded_val = len(src_string) & ~1

This simply clears the 1s bit, which is exactly what you need. Only works for ints, but len should always be integer.

The // operator is probably your best bet, but you could also use the divmod function:

rounded_val = divmod(len(src_string), 2)[0] * 2

Why not this:

rounded_val = len(src_string) - len(src_string) % 2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top