String formatting
String formatting can be very useful. it is very close to the C function sprintf() :Examples :
"My tailor is %s..." % "rich" returns "My tailor is rich..."
"Tea %d %d %s" % (4, 2, "etc.") returns "Tea 4 2 etc."
"%(itemNumber)d %(itemColor)s" % {"itemNumber":123, "itemColor":"blue"}returns "123 blue"
% codes to format strings:
Code | Description |
%s | String or any object |
%r | Equivalent to %s but uses repr() |
%c | Character |
%d | Decimal integer |
%i | Integer |
%u | Unsigned integer |
%o | Octal integer |
%x, %X | Hexadecimal integer |
%e, %E | Float exponent |
%f, %F | Float |
%g, %G | %e or %f float |
%% | '%' literal |
No comments:
Post a Comment