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

后端 未结 18 2038
面向向阳花
面向向阳花 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:15

    use String formatting

    print("If there was a birth every 7 seconds, there would be: {} births".format(births))
     # Will replace "{}" with births
    

    if you doing a toy project use:

    print('If there was a birth every 7 seconds, there would be:' births'births) 
    

    or

    print('If there was a birth every 7 seconds, there would be: %d births' %(births))
    # Will replace %d with births
    
    0 讨论(0)
  • 2020-11-28 02:16

    Python is a very versatile language. You may print variables by different methods. I have listed below five methods. You may use them according to your convenience.

    Example:

    a = 1
    b = 'ball'
    

    Method 1:

    print('I have %d %s' % (a, b))
    

    Method 2:

    print('I have', a, b)
    

    Method 3:

    print('I have {} {}'.format(a, b))
    

    Method 4:

    print('I have ' + str(a) + ' ' + b)
    

    Method 5:

    print(f'I have {a} {b}')
    

    The output would be:

    I have 1 ball
    
    0 讨论(0)
  • 2020-11-28 02:16

    On a current python version you have to use parenthesis, like so :

    print ("If there was a birth every 7 seconds", X)
    
    0 讨论(0)
  • 2020-11-28 02:17

    As of python 3.6 you can use Literal String Interpolation.

    births = 5.25487
    >>> print(f'If there was a birth every 7 seconds, there would be: {births:.2f} births')
    If there was a birth every 7 seconds, there would be: 5.25 births
    
    0 讨论(0)
  • 2020-11-28 02:17

    You can either use the f-string or .format() methods

    Using f-string

    print(f'If there was a birth every 7 seconds, there would be: {births} births')
    

    Using .format()

    print("If there was a birth every 7 seconds, there would be: {births} births".format(births=births))
    
    0 讨论(0)
  • 2020-11-28 02:18

    use string format :

    birth = 5.25487
    print(f'''
    {birth} 
    ''')
    
    0 讨论(0)
提交回复
热议问题