Monday, July 21, 2014

printf format string in Python

The format operator, % allows us to construct strings, replacing parts of the
strings with the data stored in variables.  But when the first 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.
For example, the format sequence '%d' means that the second operand should be
formatted as an integer (d stands for “decimal”):
>>> camels = 42
>>> '%d' % camels
'42'
The difference in python and c for print function is that python uses % operator again before variable names

e.g.

IN C language>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int num= 3;
float rate = 3.2;
char letter = 'A';

printf("%d, %f, %c" num, rate, letter);

output:--

3,3.2,A


IN Python >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

 num= 3
 rate = 3.2
letter = 'A'

print "%d %f %c" %(num, rate, letter)

output:--

3,3.2,A

for more about formated string refer this 

No comments:

Post a Comment