2017-08-10 58 views
0

一个Python新手问题:如何打印C画幅的python

我想在Python与C格式的参数列表打印:

agrs = [1,2,3,"hello"] 
string = "This is a test %d, %d, %d, %s" 

如何打印使用Python为:

这是一个测试1,2,3,你好

感谢。

+0

看看https:// stackoverflow。COM /问题/ 15286401 /打印多参数功能于蟒蛇 – WookieCoder

+0

我会说去看看这里的文档:https://docs.python.org/3.6/library/string.html一切都非常有据可查的有它应该是你看起来的第一个地方。 –

+0

@bouletta:我不会把它称为重复的,只是因为这个特定的问题涉及将现有的'list'格式化为顺序格式项目。的确,你可能只是盲目地做'字符串%(AGRS [0],AGRS [1],AGRS [2],AGRS [3])'和它的工作,但你不一定会明白为什么它的工作(你需要'tuple'明确和'列表(AGRS)'工作得很好。 – ShadowRanger

回答

3

字符串超载模运算符,%,为printf-style formatting,以及特殊情况下tuple!用多个值的格式,因此,所有你需要做的是从list转换为tuple

print(string % tuple(agrs)) 
+0

这很适合我,是最简单的方法,谢谢。 – KTrinh

0

看看%运营商。它接受一个字符串,这样一个元组:

print "My age is %d and my favourite char is %c" % (16, '$') 
0

元组:

实施例:

print("Total score for %s is %s " % (name, score)) 

你的情况:

print(string % tuple(agrs)) 

或者使用新样式的字符串格式:

print("Total score for {} is {}".format(name, score)) 

或者传递值作为参数,并打印将做到这一点:

print("Total score for", name, "is", score) 

Source

+0

@ShadowRanger方法的工作最适合我,因为AGRS清单参数的变量列表。 “字符串”是一种预定义的格式,所以更改它只是使其更加复杂,谢谢利亚姆。 – KTrinh

0

采用新样式格式:这些怎么样呢? (只是experementing这里) 文档:https://docs.python.org/3.6/library/string.html

args = [1,2,3,"hello"] 
string = "{}, "*(len(args)-1)+"{}" # = "{}, {}, {}, {}" 

'This is a test {}'.format(string.format(*args)) # inception! 

或者这一个:

args = [1,2,3,"hello"] 
argstring = [str(i) for i in args] 
'This is a test {}'.format(', '.join(argstring)) 

或者干脆:

args = [1,2,3,"hello"] 
'This is a test {}'.format(', '.join(map(str,args))) 

所有打印:

这是一个测试1,2,3,你好

-1
l = [1,2,3,"hello"] 
print("This is a test %d, %d, %d, %s"%(l[0],l[1],l[2],l[3])) 

希望这个作品! 干杯芽!