Skip to content

Latest commit

ย 

History

History
70 lines (56 loc) ยท 2.67 KB

File metadata and controls

70 lines (56 loc) ยท 2.67 KB

3.9.4. ๋ฌธ์ž์—ด ํฌ๋งท ์—ฐ์‚ฐ์ž

๋ฌธ์ž์—ด ํฌ๋งท ์—ฐ์‚ฐ์ž % ๋Š” 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))