Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of the backtick character in Python

Tags:

python

I'm just getting started with python. Can somebody interpret line 2 of the following code snippet? I don't understand the `num` bit. I tried to replace the backtick character with a single tick ', but then it broke. Just a detailed explanation of that line would be great.

loop_count = 1000000
irn = ''.join([`num` for num in range(loop_count)])
number = int(irn[1]) * int(irn[10]) * int(irn[100]) * int(irn[1000]) * int(irn[10000]) * int(irn[100000]) * int(irn[1000000])
print number
like image 517
Sam Heather Avatar asked Dec 12 '12 20:12

Sam Heather


2 Answers

Backticks are a deprecated alias for the repr() builtin function, so the second line is equivalent to the following:

irn = ''.join([repr(num) for num in range(loop_count)])

This uses a list comprehension to create a list of strings representing numbers, and then uses ''.join() to combine that list of strings into a single string, so this is equivalent to the following:

irn = ''
for num in range(loop_count):
    irn += repr(num)

Note that I used repr() here to be consistent with the backticks, but you will usually see str(num) to get the string representation of an int (they happen to be equivalent).

like image 193
Andrew Clark Avatar answered Oct 25 '22 01:10

Andrew Clark


  1. for num in range(loop_count) iterates over all numbers from zero up to and excluding 1,000,000
  2. num in backticks converts each number to string using the repr() function.
  3. ''.join(...) merges all those strings into one without any separators between them.
  4. irn = ... stores the result in irn.
like image 32
NPE Avatar answered Oct 25 '22 02:10

NPE