簡體   English   中英

為什么錯誤:SyntaxError: f-string: mismatched '(', '{', or '[' in a block of code發生在 Python 中?

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

我嘗試創建一個Person類,在使用 f-strings 打印時出現了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 字符串的分隔符,因此{之后的'將終止字符串,導致不匹配的{ 在字符串周圍和內部字符串使用不同的分隔符。

此外,無需在{}內使用{} 這將創建一個set對象。 使用()進行分組。

firstPart = f"My name is {self.firstName + (' ' if self.lastName != '' else '') + self.lastName} and I am {self.age}"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM