如何在字符串中包含列表

时间:2019-07-18 13:21:25

标签: python-3.x string list

我想在字符串中包含一个列表变量。像这样:

aStr = """
blah blah blah 
blah = ["one","two","three"]
blah blah
"""

我尝试了这些:

l = ["one","two","three"]
aStr = """
blah blah blah 
blah = %s
blah blah
"""%str(l)

OR

l = ["one","two","three"]
aStr = """
blah blah blah 
blah = """+str(l)+"""
blah blah
"""

不幸的是他们没有工作

3 个答案:

答案 0 :(得分:1)

您的两个摘录都几乎按照您提到的方式工作。唯一的区别是,包含列表的行在每个逗号后都有空格。随附的代码准确地提供了您想要的输出。

l = ["one","two","three"]
aStr = """
blah blah blah 
blah = %s
blah blah
"""% ('["'+'","'.join(l)+'"]')

那怎么办?

这里最有趣的部分是这个'","'.join(l).join()方法采用在点之前传递的字符串,并连接由该字符串分隔的列表的每个元素。

执行此操作的其他方式:

l = [1,2,3]
"a "+str(l)+" b"
"a {} b".format(l)
"a {name} b".format(name=l)
f"a {l} b"

答案 1 :(得分:0)

如果您只想包含列表的字符串,则可以执行以下操作:

s1 = "blah blah blah"
l = [1,2,3]
s2 = "blah blah blah"
s3 = s1 + str(l) + s2

答案 2 :(得分:-1)

如何使用f字符串。

strQ =f"""
blah blah blah 
blah = {l}
blah blah"""

这将给出:

"\nblah blah blah \nblah = ['one', 'two', 'three']\nblah blah\n"

这将在python 3.6及更高版本中工作,但在3.6以下版本中则无效。

相关问题