在 Python 3.4 中打印变量 [英] Printing variables in Python 3.4

查看:84
本文介绍了在 Python 3.4 中打印变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以语法似乎与我在 Python 2 中学到的有所不同......这是我目前所拥有的

So the syntax seems to have changed from what I learned in Python 2... here is what I have so far

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

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

The first value being an int, the second a string, and the final an int.

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

How can I alter my print statement so that it prints the variables correctly?

推荐答案

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

The syntax has changed in that print is now a function. This means that the % formatting needs to be done inside the parenthesis:1

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

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

However, since you are using Python 3.x., you should actually be using the newer str.format method:

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

虽然 % 格式尚未正式被弃用(目前),但不鼓励使用 str.format 并且很可能会被删除来自即将到来的版本中的语言(也许是 Python 4?).

Though % formatting is not officially deprecated (yet), it is discouraged in favor of str.format and will most likely be removed from the language in a coming version (Python 4 maybe?).

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

1Just a minor note: %d is the format specifier for integers, not %s.

这篇关于在 Python 3.4 中打印变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆