Introduction
The python % operator for strings is used for wildcard substitution. String and Unicode objects have one unique built-in operation: the% operator (modulo).
This is also known as a string formatting or interpolation operator.
The specified values ββof the% format (where the format is a string or a Unicode object),% of conversion specifications in the format are replaced by zero or more value elements. The effect is similar to using sprintf () in C.
If the format is a Unicode object, or if any of the objects converted using the% s conversion are Unicode objects, the result will also be a Unicode object.
Using
'd' Signed integer decimal. 'i' Signed integer decimal. 'o' Signed octal value. (1) 'u' Obsolete type β it is identical to 'd'. (7) 'x' Signed hexadecimal (lowercase). (2) 'X' Signed hexadecimal (uppercase). (2) 'e' Floating point exponential format (lowercase). (3) 'E' Floating point exponential format (uppercase). (3) 'f' Floating point decimal format. (3) 'F' Floating point decimal format. (3) 'g' Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. (4) 'G' Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. (4) 'c' Single character (accepts integer or single character string). 'r' String (converts any Python object using repr()). (5) 's' String (converts any Python object using str()). (6) '%' No argument is converted, results in a '%' character in the result.
These are values ββthat can be replaced. To replace, you simply follow the following syntax:
string%values
Examples
>>> print '%(language)s has %(number)03d quote types.' % \ ... {"language": "Python", "number": 2} Python has 002 quote types. >>> print "My name is %s"%'Anshuman' My name is Anshuman >>> print 'I am %d years old'%14 I am 14 years old >>> print 'I am %f years old' % 14.1 I am 14.1 years old
another example:
def greet(name): print 'Hello, %s!'%name
Attention!
The conversion specifier contains two or more characters and contains the following components, which must be executed in the following order:
- The character '%', which marks the beginning of the specifier.
- A mapping key (optional), consisting of a sequence of characters in brackets (for example, (name)).
- Conversion flags (optional) that affect the result of certain types of conversions.
- Minimum field width (optional). If indicated as "*" (asterisk), the actual width is read from the next element of the tuple in the values, and the object to be converted comes after the minimum field width and additional accuracy.
- Accuracy (optional) specified as '.' (dot) followed by precision. If indicated as "*" (asterisk), the actual width is read from the next element in the tuple in the values, and the value for the conversion comes after precision.
- Length modifier (optional).
- Conversion type
References
source share