2014-11-14 35 views
10

所以语法似乎已经从我在Python 2获悉改变......这里是我迄今为止印刷变量3.4

for key in word: 
    i = 1 
    if i < 6: 
     print ("%s. %s appears %s times.") % (str(i), key, str(wordBank[key])) 

第一个值是一个int,第二个字符串最后一个int。

我该如何改变我的打印语句,以便正确打印变量?

+1

'打印()'在Python 3的功能,而不是一个声明。在括号中围绕最后一行中的所有内容(除了单词“print”),并且您将全部设置。 – MattDMo 2014-11-14 21:03:56

+2

@CMac:不,你不是。你做到这一点:'print(....)',它将返回'None',然后'None%(一,二,three_strings)'。你想在'print(....)'调用中完成'something%(one,two,three_strings)'。 – 2014-11-14 21:05:14

+0

阅读[本](https://docs.python.org/3/whatsnew/3.0.html)供将来参考... – MattDMo 2014-11-14 21:05:54

回答

47

的语法已在print is now a function改变。这意味着%格式需要在括号内做:

print("%d. %s appears %d times." % (i, key, wordBank[key])) 

但是,因为你使用Python 3.x中,你实际上应使用较新的str.format方法:

print("{}. {} appears {} times.".format(i, key, wordBank[key])) 

虽然%格式不正式弃用(还),它是有利于str.format气馁,将最有可能来自于未来版本的语言删除(怪蛇4可能?)。


只是一个小提示:%d是整数格式说明,不%s

+0

谢谢,很好的回答 – algorhythm 2014-11-14 21:10:22

0

该问题似乎是错位)。在您的样品你有%print(),你应该里面移动它:

使用此:

print("%s. %s appears %s times." % (str(i), key, str(wordBank[key]))) 
4

尝试格式语法:

print ("{0}. {1} appears {2} times.".format(1, 'b', 3.1415)) 

输出:

1. b appears 3.1415 times. 

打印函数被调用,就像任何其他的功能,围绕其所有参数括号。

0

你也可以像这样格式化字符串。

>>> print ("{index}. {word} appears {count} times".format(index=1, word='Hello', count=42)) 

,输出

1. Hello appears 42 times. 

因为值被命名,它们的顺序并不重要。下面的例子输出与上面的例子相同。

>>> print ("{index}. {word} appears {count} times".format(count=42 ,index=1, word='Hello')) 

格式化字符串这种方式可以让你做到这一点。

>>> data = {'count':42, 'index':1, 'word':'Hello'} 
>>> print ("{index}. {word} appears {count} times.".format(**data)) 
1. Hello appears 42 times.