๋ฌธ์์ด ํฌ๋งท ์ฐ์ฐ์ % ๋ C์ printf() ํจ์์ ๋น์ทํฉ๋๋ค. ์ผ์ ํ ํฌ๋งท์ ๋ง์ถฐ ๋ฌธ์์ด์ ์กฐํฉํ๋ ๊ฒ์ ๋ฌธ์์ด ํฌ๋งทํ ์ด๋ผ ํฉ๋๋ค.
print "My name is %s and weight is %d kg!" % ('Zara', 21)
์์ ์ฝ๋๊ฐ ์คํ ๋๋ฉด ๋ค์๊ณผ ๊ฐ์ ๊ฒฐ๊ณผ๋ฅผ ์ถ๋ ฅ ํฉ๋๋ค.
My name is Zara and weight is 21 kg!
๋ค์์ % ์ ํจ๊ป ์ฌ์ฉํ ์ ์๋ ๋ณํ ์ง์์ด ์ ๋๋ค.
| Format Symbol | Conversion |
|---|---|
| %c | character |
| %s | string conversion via str() prior to formatting |
| %i | signed decimal integer |
| %d | signed decimal integer |
| %u | unsigned decimal integer |
| %o | octal integer |
| %x | hexadecimal integer (lowercase letters) |
| %X | hexadecimal integer (UPPERcase letters) |
| %e | exponential notation (with lowercase 'e') |
| %E | exponential notation (with UPPERcase 'E') |
| %f | floating point real number |
| %g | the shorter of %f and %e |
| %G | the shorter of %f and %E |
๊ธฐํ ์ง์๋๋ ๊ธฐํธ ๋ฐ ๊ธฐ๋ฅ์ ๋ค์ ํ์ ๋์ด๋์ด ์์ต๋๋ค.
| Symbol | Functionality |
|---|---|
| * | argument specifies width or precision |
| - | left justification |
| + | display the sign |
| <sp> | leave a blank space before a positive number |
| # | add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on whether 'x' or 'X' were used. |
| 0 | pad from left with zeros (instead of spaces) |
| % | '%%' leaves you with a single literal '%' |
| (var) | mapping variable (dictionary arguments) |
| m.n. | m is the minimum total width and n is the number of digits to display after the decimal point (if appl.) |
format ํจ์๋ ๋ฌธ์๋ฅผ ๋ค์ํ ํํ๋ก ํฌ๋งทํ ํ๋๋ฐ ์ฌ์ฉํฉ๋๋ค. ์์น๋ฅผ ๊ธฐ์ค์ผ๋ก ํ๋ ์ธ๋ฑ์คํ, ํ๋๋ช ์ ๊ธฐ์ค์ผ๋ก ํ๋ ํค์๋ํ, ๋ฆฌ์คํธ ์ธ๋ฑ์คํ์ผ๋ก ์ฌ์ฉํ ์ ์์ต๋๋ค.
sub1 = "python string!"
sub2 = "an arg"
a = "i am a %s" % sub1
b = "i am a {0}".format(sub1)
c = "with %(kwarg)s!" % {'kwarg':sub2}
d = "with {kwarg}!".format(kwarg=sub2)
print(a) # "i am a python string!"
print(b) # "i am a python string!"
print(c) # "with an arg!"
print(d) # "with an arg!"
# ์์น๋ฅผ ๊ธฐ์ค์ผ๋ก ํ ํฌ๋งทํ
print('We are the {} who say "{}!"'.format('student', 'children'))
print('We are the {0} who say "{1}!"'.format('student', 'children'))
# ํ๋๋ช
์ ๊ธฐ์ค์ผ๋ก ํ ํฌ๋งทํ
print("Age of student {name} is {age}".format(age=29, name='James'))
# object์ ์ธ๋ฑ์ค ํน์ ํค๋ฅผ ์ฌ์ฉํ์ฌ ํฌ๋งทํ
pos = [12.5, 35, 90]
print("A์ ์ขํ๋ x = {p[0]}, y = {p[1]}, z = {p[2]}".format(p=pos))