在 fstring 中使用 '{a..b}' 通配符

Using '{a..b}' wildcard in fstring

我希望使用 xarray.openmfdataset 打开一组特定的文件。例如,我想用以下代码打开 file.20180101.nc、file.20180102.nc、file20180103.nc:

xr.open_mfdataset('./file.{20180101..20180103}.nc', combine='by_coords')

开始和结束整数存储在变量 tste 中,所以我理想情况下喜欢使用这样的 fstring:

xr.open_mfdataset('./file.\{{ts}..{te}\}.nc', combine='by_coords')

其中不包含变量的'{}'被转义了。但是,我收到以下错误: SyntaxError: f-string: single '}' is not allowed

快速搜索没有找到任何解决方案,有什么好的方法可以实现吗?

f 字符串中的括号用更多括号转义。 {{ 是转义开括号,}} 是转义闭括号。

因此,这应该有效:

xr.open_mfdataset(f'./file.{{{ts}..{te}}}.nc', combine='by_coords')

bash 风格的大括号扩展不是 glob,open_mfdataset 不支持。但是,您可以传递文件名列表。

xr.open_mfdataset(
    [f'./file.{x}.nc' for x in range(ts, te)],
    combine='by_coords'
)