学习《笨办法学Python 3》时遇第9行invalid syntax错误求助
排查Python f-string的
invalid syntax错误(line 9) Hey, let's break down this syntax error you're hitting while working through Learn Python 3 the Hard Way!
你的问题与代码
你遇到了报错:invalid syntax (, line 9),但找不到代码问题。你的代码如下:
my_name = 'Zed A. Shaw' my_age = 35 # not a lie my_height = 74 # inches my_weight = 180 # lbs my_eyes = 'Blue' my_teeth = 'White' my_hair = 'Brown' print(f"Lets talk about {my_name}.") print(f"He's{my_height}inches tall.") print(f"He's{my_weight}pounds heavy.") print("Actually that's not too heavy") print(f"He's got {my_eyes}eyes and {my_hair}hair.") print(f"His teeth are usually{my_teeth} depending on the coffee") # this line is tricky, try to get it exactly right total= my_age + my_height + my_weight print(f"If I add {my_age},{my_height}, and {my_weight} I get {total}.")
错误原因
这个语法错误的核心是f-string的包裹引号与字符串内部的单引号冲突了。
看你第9行的代码:
print(f"He's{my_height}inches tall.")
你用单引号'来定义f-string,但字符串里的He's包含了一个未转义的单引号。Python会把He后面的那个'当成整个f-string的结束标记,剩下的s{my_height}inches tall.就成了无法解析的无效代码——这就是为什么报错指向第9行。
同样的问题也存在于第10行的print(f"He's{my_weight}pounds heavy.")中。
修复方案
有两种简单的修复方式:
换用双引号包裹f-string
把包裹f-string的单引号换成双引号",这样内部的单引号就不会触发字符串提前结束了,同时建议给变量前后加空格让输出语句更通顺:print(f"He's {my_height} inches tall.") print(f"He's {my_weight} pounds heavy.")转义内部的单引号
在字符串内部的单引号前加反斜杠\,告诉Python这是字符串内容的一部分,不是结束标记:print(f"He\'s {my_height} inches tall.") print(f"He\'s {my_weight} pounds heavy.")
额外小优化
顺便提一下,你可以给其他f-string里的变量也加上空格,让输出的句子更自然,比如第12行可以改成:
print(f"His teeth are usually {my_teeth}, depending on the coffee.")
内容的提问来源于stack exchange,提问作者Dean Walker
相关产品推荐
相关产品推荐

