[英]Avoiding None in f-string
If I have an f-string where one of the parameters may be None
, is there a way to automatically omit it from the string?如果我有一个 f 字符串,其中一个参数可能是None
,有没有办法从字符串中自动省略它?
f'{first_name} {prefix} {last_name}'
If prefix
is None
then this string will render as Arnold None Weber
.如果prefix
为None
则此字符串将呈现为Arnold None Weber
。
I tried f'{first_name} {prefix or ''} {last_name}'
but that's a syntax error.我试过f'{first_name} {prefix or ''} {last_name}'
但这是一个语法错误。
I tried f'{first_name} {prefix or ''} {last_name}' but that's a syntax error.我试过 f'{first_name} {prefix or ''} {last_name}' 但这是一个语法错误。
The only reason it's a syntax error is that you tried to put single quotes inside single quotes.它是语法错误的唯一原因是您试图将单引号放在单引号内。 All of the usual ways of fixing it will work:所有通常的修复方法都可以工作:
f'{first_name} {prefix or ""} {last_name}'
f"{first_name} {prefix or ''} {last_name}"
f"""{first_name} {prefix or ''} {last_name}"""
However, notice that this doesn't quite do what you want.但是,请注意,这并不能完全满足您的要求。 You won't get Arnold Weber
, but Arnold Weber
, because the spaces on either end aren't conditional.你不会得到Arnold Weber
,而是Arnold Weber
,因为两端的空格不是有条件的。 You could do something like this:你可以这样做:
f'{first_name} {prefix+" " if prefix else ""}{last_name}'
f'{first_name} {prefix or ""}{" " if prefix else ""}{last_name}'
… but at that point, I don't think you're getting the conciseness and readability benefits of f-strings anymore. ……但在那一点上,我认为您不再获得 f-strings 的简洁性和可读性优势。 Maybe consider something different, like:也许考虑一些不同的东西,比如:
' '.join(part for part in (first_name, prefix, last_name) if part)
' '.join(filter(None, (first_name, prefix, last_name)))
Not that this is shorter —but the logic is a lot clearer.并不是说这更短——但逻辑要清晰得多。
Of course it's a syntax error;当然是语法错误; you broke your string.你弄断了绳子。
f'{first_name} {prefix or ""} {last_name}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.