How can I print variable and string on same line in Python?

后端 未结 18 2098
面向向阳花
面向向阳花 2020-11-28 01:45

I am using python to work out how many children would be born in 5 years if a child was born every 7 seconds. The problem is on my last line. How do I get a variable to work

18条回答
  •  北海茫月
    2020-11-28 02:09

    Two more

    The First one

    >>> births = str(5)
    >>> print("there are " + births + " births.")
    there are 5 births.
    

    When adding strings, they concatenate.

    The Second One

    Also the format (Python 2.6 and newer) method of strings is probably the standard way:

    >>> births = str(5)
    >>>
    >>> print("there are {} births.".format(births))
    there are 5 births.
    

    This format method can be used with lists as well

    >>> format_list = ['five', 'three']
    >>> # * unpacks the list:
    >>> print("there are {} births and {} deaths".format(*format_list))  
    there are five births and three deaths
    

    or dictionaries

    >>> format_dictionary = {'births': 'five', 'deaths': 'three'}
    >>> # ** unpacks the dictionary
    >>> print("there are {births} births, and {deaths} deaths".format(**format_dictionary))
    there are five births, and three deaths
    

提交回复
热议问题