Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在f字符串中避免无_Python_Python 3.x_F String - Fatal编程技术网

Python 在f字符串中避免无

Python 在f字符串中避免无,python,python-3.x,f-string,Python,Python 3.x,F String,如果我有一个f字符串,其中一个参数可能是None,有没有办法从字符串中自动忽略它 f'{first_name}{prefix}{last_name}' 如果prefix为None,则此字符串将呈现为Arnold None-Weber 我试过f'{first\u name}{prefix或'}{last\u name}',但那是语法错误。当然是语法错误;你把绳子弄断了 f'{first_name} {prefix or ""} {last_name}' 我尝试了f'{first_name}{pr

如果我有一个f字符串,其中一个参数可能是
None
,有没有办法从字符串中自动忽略它

f'{first_name}{prefix}{last_name}'

如果
prefix
None
,则此字符串将呈现为
Arnold None-Weber


我试过
f'{first\u name}{prefix或'}{last\u name}'
,但那是语法错误。

当然是语法错误;你把绳子弄断了

f'{first_name} {prefix or ""} {last_name}'
我尝试了f'{first_name}{prefix或'}{last_name}',但这是一个语法错误

这是一个语法错误的唯一原因是您试图将单引号放在单引号内。所有常用的修复方法都会起作用:

f'{first_name} {prefix or ""} {last_name}'
f"{first_name} {prefix or ''} {last_name}"
f"""{first_name} {prefix or ''} {last_name}"""
但是,请注意,这并不能完全满足您的需要。您不会得到
Arnold-Weber
,而是
Arnold-Weber
,因为两端的空格都不是有条件的。你可以这样做:

f'{first_name} {prefix+" " if prefix else ""}{last_name}'
f'{first_name} {prefix or ""}{" " if prefix else ""}{last_name}'
…但在这一点上,我认为您不再能获得f字符串的简洁性和可读性优势。也许考虑不同的东西,比如:

' '.join(part for part in (first_name, prefix, last_name) if part)
' '.join(filter(None, (first_name, prefix, last_name)))

并不是说它更短,而是逻辑更清晰。

带反斜杠的那个不起作用-表达式中不允许使用反斜杠,除非他们在3.7中对其进行了更改。我更喜欢最后一个选项
“”。连接(过滤器(无,(名字,前缀,姓氏))