In addition to "%" as a remainder operator, Python has a method of using it as a format operator used for strings. (There is a similar usage in C language)
Addendum (2017/05/22): In python3, there are different methods such as format method, and the method using% operator is not recommended (see the comment at the bottom).
>>> #Uninflected word(python2)
>>> print 'Hello, %s' % 'world!'
Hello, world!
>>> #Uninflected word(python3)
>>> print('Hello, %s' % 'world!')
Hello, world!
>>> #If there are multiple(python2)
>>> print 'My name is %s %s.' % ('python', 'qiita')
My name is python qiita.
>>> #General form without flag(python2)
>>> print '%(Conversion type)' % (Conversion source)
>>> #General form with flag(python2)
>>> print '%(flag)(Conversion type)' % (Conversion source)
Conversion type | meaning |
---|---|
'd' | Signed decimal integer |
'i' | Signed decimal integer |
'x' | Signed hexadecimal number(Lowercase) |
'X' | Signed hexadecimal number(uppercase letter) |
'e' | Floating point number in exponential notation(Lowercase) |
'E' | Floating point number in exponential notation(uppercase letter) |
'f' | Decimal floating point number |
'F' | Decimal floating point number |
'c' | One character |
'r' | String(repr()Convert with) |
's' | String(str()Convert with) |
flag | meaning |
---|---|
'0' | Zero padding for numeric types |
'-' | Left justify the converted value |
' ' | For signed conversions with positive numbers, leave a space before |
'+' | Prepend a code character to the conversion |
Numbers(Non-zero) | Output to that number of digits |
-5.6.2. String formatting operations
Recommended Posts