Format Operator

With format operator % we can construct strings, replacing parts of the strings with the data stored in variables. When applied to integers, % is the modulus operator. But when the frist operand is a string, % is the format operator.
The first operand is the format string, which contains one or more format sequences that specify how the second operand is formatted. The result is a string.
>>> camels = 42
>>> '%d' % camels
'42'
The result is the string ‘42’, which is not to be confused with the integer value 42. A format sequence can appear anywhere in the string, so you can embed a value in a sentence:
>>> camels = 42
>>> 'I have spotted %d camels.' % camels
'I have spotted 42 camels.'
The following example uses ‘%d’ to format an integer, ‘%g’ to format a floating point number, and ‘%s’ to format a string:
>>> 'In %d years I have spotted %g %s.' %(3, 0.1, 'camels')
'In 3 years I have spotted 0.1 camels.'
The number of elements in the tuple has to match the number of format sequences in the string. Also, the types of elements have to match the format sequences:
>>> '%g %g %g' %(0.1, 0.1)
Traceback (most recent call last): 
  File "", line 1, in 
TypeError: not enough arguments for format string
>>> '%d' % 'dounats'
Traceback (most recent call last):
  File "", line 1, in 
TypeError: %d format: a number is required, not str

If the fist example, ther aren’t enough elements and in the secon the element is wrong type. 

Nema komentara:

Objavi komentar