print variable and a string in python

前端 未结 7 2075
逝去的感伤
逝去的感伤 2020-12-07 23:49

Alright, I know how to print variables and strings. But how can I print something like \"My string\" card.price (it is my variable). I mean, here is my code: print \"

相关标签:
7条回答
  • '''
    
    If the python version you installed is 3.6.1, you can print strings and a variable through
    a single line of code.
    For example the first string is "I have", the second string is "US
    Dollars" and the variable, **card.price** is equal to 300, we can write
    the code this way:
    
    '''
    
    print("I have", card.price, "US Dollars")
    
    #The print() function outputs strings to the screen.  
    #The comma lets you concatenate and print strings and variables together in a single line of code.
    
    0 讨论(0)
  • 2020-12-08 00:34

    From what I know, printing can be done in many ways

    Here's what I follow:

    Printing string with variables

    a = 1
    b = "ball"
    print("I have", a, b)
    

    Versus printing string with functions

    a = 1
    b = "ball"
    print("I have" + str(a) + str(b))
    

    In this case, str() is a function that takes a variable and spits out what its assigned to as a string

    They both yield the same print, but in two different ways. I hope that was helpful

    0 讨论(0)
  • 2020-12-08 00:37

    By printing multiple values separated by a comma:

    print "I have", card.price
    

    The print statement will output each expression separated by spaces, followed by a newline.

    If you need more complex formatting, use the ''.format() method:

    print "I have: {0.price}".format(card)
    

    or by using the older and semi-deprecated % string formatting operator.

    0 讨论(0)
  • 2020-12-08 00:42

    If you are using python 3.6 and newer then you can use f-strings to do the task like this.

    print(f"I have {card.price}")
    

    just include f in front of your string and add the variable inside curly braces { }.

    Refer to a blog The new f-strings in Python 3.6: written by Christoph Zwerschke which includes execution times of the various method.

    0 讨论(0)
  • 2020-12-08 00:42

    All answers above are correct, However People who are coming from other programming language. The easiest approach to follow will be.

    variable = 1

    print("length " + format(variable))

    0 讨论(0)
  • 2020-12-08 00:43

    Assuming you use Python 2.7 (not 3):

    print "I have", card.price (as mentioned above).

    print "I have %s" % card.price (using string formatting)

    print " ".join(map(str, ["I have", card.price])) (by joining lists)

    There are a lot of ways to do the same, actually. I would prefer the second one.

    0 讨论(0)
提交回复
热议问题