简体   繁体   中英

Why does the error: SyntaxError: f-string: mismatched '(', '{', or '[' in a block of code occur in Python?

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}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM