I have tried to make a Person
class and while printing using f-strings an SyntaxError
came up. Do you know why?
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 '['
Does anyone know why this is happening? (like a typo) I think I am just not looking closely, or is there a reason to this?
† some random number, not my real age
Since you're using '
as the delimiters of the f-string, the '
after {
will terminate the string, resulting in an unmatched {
. Use different delimiters around the string and for the strings that are inside.
Also, there's no need to use {}
inside {}
. That will create a set
object. Use ()
for grouping.
firstPart = f"My name is {self.firstName + (' ' if self.lastName != '' else '') + self.lastName} and I am {self.age}"