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

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

    If you want to work with python 3, it's very simple:

    print("If there was a birth every 7 second, there would be %d births." % (births))
    
    0 讨论(0)
  • 2020-11-28 02:21

    Use , to separate strings and variables while printing:

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

    , in print function separates the items by a single space:

    >>> print("foo", "bar", "spam")
    foo bar spam
    

    or better use string formatting:

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

    String formatting is much more powerful and allows you to do some other things as well, like padding, fill, alignment, width, set precision, etc.

    >>> print("{:d} {:03d} {:>20f}".format(1, 2, 1.1))
    1 002             1.100000
      ^^^
      0's padded to 2
    

    Demo:

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

    Just use , (comma) in between.

    See this code for better understanding:

    # Weight converter pounds to kg
    
    weight_lbs = input("Enter your weight in pounds: ")
    
    weight_kg = 0.45 * int(weight_lbs)
    
    print("You are ", weight_kg, " kg")
    
    0 讨论(0)
  • 2020-11-28 02:22

    Slightly different: Using Python 3 and print several variables in the same line:

    print("~~Create new DB:",argv[5],"; with user:",argv[3],"; and Password:",argv[4]," ~~")
    
    0 讨论(0)
  • 2020-11-28 02:26

    You would first make a variable: for example: D = 1. Then Do This but replace the string with whatever you want:

    D = 1
    print("Here is a number!:",D)
    
    0 讨论(0)
  • 2020-11-28 02:27

    If you use a comma inbetween the strings and the variable, like this:

    print "If there was a birth every 7 seconds, there would be: ", births, "births"
    
    0 讨论(0)
提交回复
热议问题