ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 파이썬 - 포맷팅 예시
    파이썬 2017. 11. 26. 21:25

    >>> person = {'name': 'jenn', 'age': 23}

    >>> sentence = 'my name is {} and i am {} years old.'.format(person['name'], person['age'])

    >>> print(sentence)

    my name is jenn and i am 23 years old.






    >>> person = {'name': 'jenn', 'age': 23}

    >>> sentence = 'my name is {0[name]} and i am {0[age]} years old.'.format(person)

    >>> print(sentence)

    my name is jenn and i am 23 years old.






    >>> l = ['jenn', 23]

    >>> sentence = 'my name is {0[0]} and i am {0[1]} years old.'.format(l)

    >>> print(sentence)

    my name is jenn and i am 23 years old.






    >>> tag = 'hi'

    >>> text = ' this is a headline'

    >>> sentence = '<{0}>{1}</{0}>'.format(tag, text)

    >>> print(sentence)

    <hi> this is a headline</hi>





    >>> class person():

    def __init__(self, name, age):

    self.name = name

    self.age = age

    >>> pl = person('Jack', '33')


    >>> sentence = 'My name is {0.name} and I am {0.age} old.' .format(pl)

    >>> print(sentence)

    My name is Jack and I am 33 old.




    >>> sentence = 'My name is {name} and I am {age} years old.' .format(name='Jenn', age='30')

    >>> print(sentence)

    My name is Jenn and I am 30 years old.




    >>> person = {'name': 'Jenn', 'age': 23}

    >>> sentence = 'My name is {name} and I an {age} years old.'.format(**person)

    >>> print(sentence)

    My name is Jenn and I an 23 years old.




    숫자


    >>> for i in range(1,11):

    sentence = 'The value is {:02}'.format(i)   # {} -> {:2}, 2자릿수로 바꿈.

    print(sentence)


    The value is 01

    The value is 02

    The value is 03

    The value is 04

    The value is 05

    The value is 06

    The value is 07

    The value is 08

    The value is 09

    The value is 10




    >>> pi = 3.14159265

    >>> sentence = 'pi is equal to {:.3f}' .format(pi)   #.nf -> 소수점 자릿수n

    >>> print(sentence)

    pi is equal to 3.142




    >>> sentence = '1 MB is equal to {:,} bytes'.format(1000**2)

    >>> print(sentence)

    1 MB is equal to 1,000,000 bytes




    >>> my_date = datetime.datetime(2017, 11, 26, 21, 21, 40)

    >>> print(my_date)

    2017-11-26 21:21:40




    >>> my_date = datetime.datetime(2017, 11, 26, 21, 21, 40)

    >>> sentence = '{:%B %d, %Y}'.format(my_date)

    >>> print(sentence)

    November 26, 2017