Answer a question

I want to use f string formatting instead of print. However, I get these errors: Unterminated expression in f-string; missing close brace Expected ')'

var="ab-c"
f"{var.replace("-","")}text123"

I tried to use single quote f'' and also double brackets but neither of them worked. Any idea about how to fix this?

Answers

For f"{var.replace("-","")}text123", Python parses f"{var.replace(" as a complete string, which you can see has an opening { and opening (, but then the string is terminated. It first expected a ) and eventually a }, hence the error you see.

To fix it, Python allows ' or " to enclose a string, so use one for the f-string and the other for inside the string:

f"{var.replace('-','')}text123"

or:

f'{var.replace("-","")}text123'

Triple quotes can also be used if internally you have both ' and "

f'''{var.replace("-",'')}text123'''

or:

f"""{var.replace("-",'')}text123"""
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐