【发布时间】:2020-03-09 16:50:58
【问题描述】:
我尝试创建一个Person 类,并且在使用 f 字符串打印时出现了一个SyntaxError。你知道为什么吗?
class Person:
def __init__(self, age, firstName, lastName='', hobbies=None):
self.age = age
self.firstName = firstName
self.lastName = lastName
self.hobbies = hobbies
def printDescription():
firstPart = f'My name is {self.firstName + {' ' if self.lastName != '' else ''} + self.lastName} and I am {self.age}'
secondPart = f', also I like {self.hobbies}' if self.hobbies else ''
print(firstPart + secondPart)
me = Person.__init__(me, 500†, 'Ken', 'Tran', 'programming')
me.printDescription()
SyntaxError: f-string: mismatched '(', '{', or '['
有人知道为什么会这样吗? (就像一个错字)我想我只是没有仔细观察,还是有原因?
† 一些随机数,不是我的真实年龄
【问题讨论】:
-
f-string 中的每个变量都应该用大括号括起来。例如你有:
{self.firstName + {。你也有:like {self.hobbies}看起来不错。 -
我会推荐一个返回全名的
@property方法。 -
你想在 fstring 括号中做逻辑吗?
标签: python f-string square-bracket braces