how to print out a string and list in one line-python

…衆ロ難τιáo~ 提交于 2021-02-04 13:33:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!