在Python 3.4中打印变量

alg*_*thm 36 python printing variables syntax

所以语法似乎已经从我在Python 2中学到的东西改变了......这就是我到目前为止所拥有的

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

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

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

iCo*_*dez 101

语法已经改变,print现在是一个函数.这意味着%格式化需要在括号内完成:1

print("%d. %s appears %d times." % (i, key, wordBank[key]))
Run Code Online (Sandbox Code Playgroud)

但是,由于您使用的是Python 3.x.,实际上您应该使用更新的str.format方法:

print("{}. {} appears {} times.".format(i, key, wordBank[key]))
Run Code Online (Sandbox Code Playgroud)

虽然%格式化还没有被正式弃用(但是),但是它不鼓励使用,str.format并且很可能会在即将到来的版本中删除该语言(Python 4可能会?).


1只是一个小注:%d是整数的格式说明符,而不是%s.

  • 根据[wwii的答案](https:// stackoverflow),非常笨拙的Python 3.6之前的语法现已被[f-strings](https://docs.python.org/3/whatsnew/3.6.html)取代.com / a / 48870661/202229)。您能否更新您的答案,这已经过时了吗? (3认同)

wwi*_*wii 39

版本3.6+:使用格式化的字符串文字,简称f字符串

print(f"{i}. {key} appears {wordBank[key]} times.")
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的答案,在3.6 / 3.7中 (2认同)

hor*_*rns 8

尝试使用格式语法:

print ("{0}. {1} appears {2} times.".format(1, 'b', 3.1415))
Run Code Online (Sandbox Code Playgroud)

输出:

1. b appears 3.1415 times.
Run Code Online (Sandbox Code Playgroud)

就像其他任何函数一样,调用print函数,其所有参数都带有括号。


Eri*_*n V 5

您还可以像这样格式化字符串:

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

哪些输出

1. Hello appears 42 times.
Run Code Online (Sandbox Code Playgroud)

因为值是命名的,所以它们的顺序无关紧要。使下面的示例输出与上面的示例相同。

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

以这种方式格式化字符串允许您执行此操作。

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