print ("Hello World") print ("{} World").format(Hello)
我正在研究我的第一个"Hello World"程序,我可以通过使用print函数和一个简单的字符串文本来实现它,但是当我尝试使用 .format 时,它给了我错误:
.format
AttributeError: 'NoneType' object has no attribute 'format'
这是说我需要为 .format 初始化一个变量,还是我错过了什么?
你的括号错了
print("Hello World") print("{} World".format('Hello'))
注意 - 错误
format 函数是 str 的属性,因此需要在字符串上调用它
format
str
除非声明, Hello 是一个字符串,应为 'Hello'
Hello
'Hello'
对于Py2,你可以做到
print "{} World".format('Hello')
函数 print 返回 None ,以便's obviously what you'从第二个语句的开头返回,即
print
None
print ("{} World")
在 None 的返回值上,然后调用 .format(Hello) - 即使在代码中的某个地方分配了一个名为 Hello 的变量(并且're not showing it to us!), you'在 print 调用返回的 None 上调用了 .format 方法,这没有任何意义 .
.format(Hello)
相反,你想在 string "{} World" 上调用 .format - 所以在字符串之后和点之前的封闭式显然是一个可怕的错误!将 ) 移动到语句的末尾, after 对该字符串的 format 调用 .
"{} World"
)
此外, is Hello 要为其格式化值的变量的名称?我当然希望不会,否则为什么你没有告诉我们变量被分配?!我怀疑你想要格式化 constant string 并且只是心不在焉地忘记 put it in quotes (显示它是一个常量,而不是变量的名称!) - 'Hello' , not Hello 没有引号!这就是你应该传递给 .format 呼叫的正确形式......!
2 回答
你的括号错了
注意 - 错误
format
函数是str
的属性,因此需要在字符串上调用它除非声明,
Hello
是一个字符串,应为'Hello'
对于Py2,你可以做到
函数
print
返回None
,以便's obviously what you'从第二个语句的开头返回,即在
None
的返回值上,然后调用.format(Hello)
- 即使在代码中的某个地方分配了一个名为Hello
的变量(并且're not showing it to us!), you'在print
调用返回的None
上调用了.format
方法,这没有任何意义 .相反,你想在 string
"{} World"
上调用.format
- 所以在字符串之后和点之前的封闭式显然是一个可怕的错误!将)
移动到语句的末尾, after 对该字符串的format
调用 .此外, is
Hello
要为其格式化值的变量的名称?我当然希望不会,否则为什么你没有告诉我们变量被分配?!我怀疑你想要格式化 constant string 并且只是心不在焉地忘记 put it in quotes (显示它是一个常量,而不是变量的名称!) -'Hello'
, notHello
没有引号!这就是你应该传递给.format
呼叫的正确形式......!