我是 Python 新手,所以我一直在进行自己的一组练习,以简单地开始记住基本函数和语法。
我正在使用PyCharmIDE 和 Python 3.4。我在进行一些基本的字符串和整数连接练习时遇到了问题。下面的每个实例都抛出不支持的操作数类型。 Stack Overflow 上有几个线程清楚地说明了正确的串联语法,但上述错误消息仍然困扰着我。
print ("Type string: ") + str(123)
print ("Concatenate strings and ints "), 10
在 Python 3+ 中,print
是一个函数,因此必须使用括号之间的参数来调用它。所以看看你的例子:
print ("Type string: ") + str(123)
它实际上等同于:
var = print("Type string: ")
var + str(123)
Since print
不返回任何内容(在 Python 中,这意味着None
),这相当于:
None + str(123)
这显然会给出错误。
话虽这么说,关于你试图做什么,你want做到这一点非常简单:通过print
function您要打印的内容,可以通过多种方式完成:
print ("Type string: " + str(123))
# Using format method to generate a string with the desired contents
print ("Type string: {}".format(123))
# Using Python3's implicit concatenation of its arguments, does not work the same in Python2:
print ("Type string:", str(123)) # Notice this will insert a space between the parameters
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)