f-string:与函数调用不匹配的“(”

问题描述 投票:0回答:5

我试图在 python 中使用 f 字符串将一些变量替换为我正在打印的字符串,但出现语法错误。 这是我的代码:

print(f"{index+1}. {value[-1].replace("[Gmail]/", '')}")

我在添加替换后才开始遇到问题。我已经检查过很多次了,我确信我没有漏掉括号。我知道还有很多其他方法可以实现此目的,其中一些可能更好,但我很好奇为什么这行不通。

python quotes function-call quoting f-string
5个回答
72
投票

您的问题是双引号内的双引号。 例如,

  • 好的 -->
    f"hello ' this is good"
  • 好的 -->
    f'hello " this is good'
  • 错误 -->
    f"hello " this breaks"
  • 错误 -->
    f'hello ' this breaks'

这个应该可以正常工作:

print(f"{index+1}. {value[-1].replace('[Gmail]/', '')}")

超出范围,但我仍然不建议您在

replace
内使用
f-string
。我认为最好将其移至临时变量。


2
投票

这个好像不行

x = 'hellothere'
print(f"replace {x.replace("hello",'')}")

错误

    print(f"replace {x.replace("hello",'')}")
                                ^
SyntaxError: f-string: unmatched '('

试试这个吧

x = 'hellothere'
print(f"replace {x.replace('hello','')}")

单引号

'hello'
输出是

replace there

2
投票

我遇到了同样的问题,将括号内的所有双引号更改为单引号。它应该可以工作 例如来自 print( f" 水 : {资源["水"] } " ) 到
print( f" 水 : {资源['水'] } " )


0
投票

另一种进行字符串格式化的方法(我认为这可以提高可读性):

print("{0}. {1}".format(index+1, 
                        value[-1].replace("[Gmail]/", "")))

0
投票

我发现这在 python 版本 3.12 中已“修复”,您现在可以在 f 字符串中使用相同的引号类型。

这在这个堆栈溢出响应

中也提到过
© www.soinside.com 2019 - 2024. All rights reserved.