2011-09-27 26 views
61

我在Python 2.6.5中构建了一个字符串s,它将有不同数量的%s标记,它们与列表x中的条目数相匹配。我需要写出一个格式化的字符串。以下不起作用,但表明我正在尝试做什么。在这个例子中,有三个%s令牌,并且该列表有三个条目。使用Python字符串格式化与列表

s = '%s BLAH %s FOO %s BAR' 
x = ['1', '2', '3'] 
print s % (x) 

我想输出字符串为:的

1 BLAH 2 FOO 3 BAR

回答

17

在此之后resource page,如果x的长度不同,我们可以使用:

', '.join(['%.2f']*len(x)) 

创建一个占位符从每个元素列表x。这里是例子:

x = [1/3.0, 1/6.0, 0.678] 
s = ("elements in the list are ["+', '.join(['%.2f']*len(x))+"]") % tuple(x) 
print s 
>>> elements in the list are [0.33, 0.17, 0.68] 
74
print s % tuple(x) 

代替

print s % (x) 
+2

'(x)'与'x'是一样的。将单个标记放在括号中对Python没有意义。你通常在'foo =(bar,)'中放入括号以便于阅读,但是'foo = bar'完全一样。 – patrys

+6

'print s%(x)'是OP写的,我只是引用他/她。 – infrared

+0

我只是提供了一个语言提示,而不是批评你的答案(实际上我已经为它+1了)。你没有写'foo =(bar,)':) – patrys

99

你应该看看到蟒蛇的format方法。然后,你可以定义你的格式化字符串是这样的:

>>> s = '{0} BLAH {1} BLAH BLAH {2} BLAH BLAH BLAH' 
>>> x = ['1', '2', '3'] 
>>> print s.format(*x) 
'1 BLAH 2 BLAH BLAH 3 BLAH BLAH BLAH' 
+0

Python 2.6+。 – agf

+1

OP使用2.6.5 - > ok – glglgl

+1

OP的问题不是方法,而是参数的格式。 '%'操作符只能解包元组。 – patrys

11

因为我刚刚得知这个很酷的事情(索引到数组从格式字符串中)我加入到这个老问题。

s = '{x[0]} BLAH {x[1]} FOO {x[2]} BAR' 
x = ['1', '2', '3'] 
print s.format (x=x) 

不过,我还没有想出如何做切片(格式字符串'"{x[2:4]}".format...,内部),很想弄明白如果任何人有一个想法,但是我怀疑你根本就做不到那。

+0

我对你的切片用例有点好奇。 – Michael

+0

我真的没有一个...我想我只是觉得它会整齐地做 –

4

这是一个有趣的问题!使用变长列表的.format方法处理此问题的另一种方法是使用充分利用列表解包的功能。在下面的例子中,我没有使用任何花哨的格式,但可以很容易地进行更改以满足您的需求。

list_1 = [1,2,3,4,5,6] 
list_2 = [1,2,3,4,5,6,7,8] 

# Create a function to easily repeat on many lists: 
def ListToFormattedString(alist): 
    # Each item is right-adjusted, width=3 
    formatted_list = ['{:>3}' for item in alist] 
    s = ','.join(formatted_list) 
    return s.format(*alist) 

# Example output: 
>>>ListToFormattedString(list_1) 
' 1, 2, 3, 4, 5, 6' 
>>>ListToFormattedString(list_2) 
' 1, 2, 3, 4, 5, 6, 7, 8' 
-1

,也有可能在python 3.6+做到:

x = ['1', '2', '3'] 
print(f"{x[0]} BLAH {x[1]} FOO {x[2]} BAR") 
0

这里有一个小即兴回答使用格式列表上的print()。

如何:(PY3)

sample_list = ['cat', 'dog', 'bunny', 'pig'] 
print("Your list of animals are: {}, {}, {} and {}".format(*sample_list)) 

在这里阅读文档使用format