0

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:

  • the use of two forward slashes here
  • the effect of the { } brackets in the string

Explanations would be much appreciated - thanks!

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.