问题
a=[1,2,3]
print "the list is :%"%(a)
I want to print out one line like this: the list is:[1,2,3]
I can not make it within one line and I have to do in this way:
print " the list is :%"
print a
I am wondering whether I can print out something that combine with string formatting and a list in ONE line.
回答1:
The simplest way is what CodeHard_or_HardCode said in the comments. For Python 3 it would be:
a=[1,2,3]
print('This is a list', a)
This is a list [1, 2, 3]
回答2:
I suggest using the string format method, as it is recommended over the old %
syntax.
print("the list is: {}".format(a))
回答3:
At least in Python 2.7.4., this will work:
print " the list is " + str(a)
回答4:
Try this:
a = [1,2,3]
print("the list is: %s" % a)
回答5:
print(f"the list is: {[1,2,3]}")
you will need to use python 3.7.1 or higher I believe, as this is when they added string interpolation
来源:https://stackoverflow.com/questions/25733737/how-to-print-out-a-string-and-list-in-one-line-python