如何在一行line-python中打印出一个字符串和列表

use*_*551 5 python formatting

a=[1,2,3]
print "the list is ?%"%(a)
Run Code Online (Sandbox Code Playgroud)

我想打印出这样一行:the list is?[1,2,3] 我不能在一行内完成,我必须这样做:

print " the list is :%"
print a
Run Code Online (Sandbox Code Playgroud)

我想知道我是否可以打印出与字符串格式和一行列表相结合的内容.

mot*_*oto 11

最简单的方法是CodeHard_or_HardCode在评论中所说的内容.对于Python 3,它将是:

a=[1,2,3]
print('This is a list', a)

This is a list [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)


Rog*_*Fan 6

我建议使用 stringformat方法,因为它优于旧%语法。

print("the list is: {}".format(a))
Run Code Online (Sandbox Code Playgroud)


use*_*028 1

尝试这个:

a = [1,2,3]
print("the list is: %s" % a)
Run Code Online (Sandbox Code Playgroud)

  • `%s` 已被弃用。 (2认同)
  • 好吧,我不确定它是否已被正式弃用,但绝对不鼓励这样做。事实上,格式化列表的这个问题在[文档](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting)中直接引用:“这里描述的格式化操作[%] 表现出各种怪癖,导致许多常见错误(例如无法正确显示元组和字典)。” (2认同)