Jim Eisenberg
Jim Eisenberg

Reputation: 1500

Explaining advanced string formatting python

I'm trying to understand how this answer on Code Golf works, turning integers into french licence plates with the following code:

lambda n:f"%c%c-{n%1000:03}-%c%c"%(*(65+n//1000//26**i%26for i in[3,2,1,0]),)

I understand '%c' with 65 + n on a % 26 number to get the letters, and I understand % 1000 : 03 for getting 3-0 padded numbers up to 999. However I can't find anything on the following:

Explanations would be much appreciated - thanks!

Upvotes: 0

Views: 85

Answers (2)

Djaouad
Djaouad

Reputation: 22776

The // is for integer division (it only keeps the integer part of a division operation result, similar to int(n/m)).

Example:

>>> n, m = 10, 7
>>> n / m
1.4285714285714286
>>> n // m
1

The {} in f-strings is used to evaluate an expression from within the string itself.

Example:

>>> x = 5
>>> print(f"x^2 = {x**2}")
x^2 = 25

Upvotes: 2

tituszban
tituszban

Reputation: 5152

The double slashes (//) are integer division. Back in Python2 the / was ambiguous. It meant different things, depending on the types on the two sides. This caused a fair amount of confusion, so in Python3 it has been split to / and //, where / is always standard division, if you run 5/3 it will always be 1.66..., no matter if 5 and 3 are ints or floats. Meanwhile // is always integer division, which divides than floors the number. (so 3.4 // 1.2 is 2)

f'...{expression}...' is a so called f-string. It takes the the value in the {} brackets, and formats it in place. It's similar '...{}...'.format(expression). It's tricky because the example uses both f strings and % formatting.

Upvotes: 2

Related Questions