问题描述
我正在尝试在 python 中使用 f-strings 将一些变量替换为我正在打印的字符串,但出现语法错误。 这是我的代码:
print(f"{index+1}. {value[-1].replace("[Gmail]/",'')}")
我只是在添加替换后才开始遇到问题。我已经检查了很多次,我确信我没有遗漏一个括号。我知道有很多其他方法可以实现这一点,其中一些可能更好,但我很好奇为什么这不起作用。
解决方法
这个好像不行
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
,
您的问题是双引号内的双引号。 这个应该可以正常工作:
print(f"{index+1}. {value[-1].replace('[Gmail]/','')}")
超出范围,但我仍然不建议您在 replace
内使用 f-string
。我认为最好将其移至临时变量。
另一种进行字符串格式化的方法(我认为这提高了可读性):
print("{0}. {1}".format(index+1,value[-1].replace("[Gmail]/","")))