I'm studying the code of an open source project. The code it's written in python and unfortunately I'm not so experienced with it. I found a lot of statement in the code like this:
print "the string is %s" % (name_of_variable, )
I know that, similarly to c language, this is a way to properly format the output, but I really don't understand what is the meaning of the comma right after the "name_of_variable" within the parenthesis.
I searched through python documentation, but I didn't find nothing about that kind of statement. Does anyone know what is its meaning?
The trailing comma is a way to create a one-element tuple. Normally you create a tuple by listing a set of values or variables in parentheses, separated by a comma:
my_tuple = (1, 2, 3)
However, the parentheses are not actually necessary. You can create a tuple like this:
my_tuple = 1, 2, 3
Of course, this raises an issue with one-element tuples. If you leave out the parentheses, you're just assigning a variable to a single variable:
my_tuple = 1 # my_tuple is the integer 1, not a one-element tuple!
But using parentheses is ambiguous, since surrounding a value in parentheses is totally legal:
my_tuple = (1) # my_tuple is still the integer 1, not a one-element tuple
So you indicate a one-element tuple by adding a trailing comma:
my_tuple = 1,
# or, with parentheses
my_tuple = (1,)
String formatting takes a tuple as an arguments, so if you're using a one-element tuple, you'd use a trailing comma. (Of course, string formatting has special handling for cases in which you are passing only one variable to be formatted—you can just use a value in those cases, instead of a tuple.)