【问题标题】:Single liner to add text to filename before extension with f-strings在使用 f 字符串扩展之前将文本添加到文件名的单行
【发布时间】:2020-10-11 15:12:57
【问题描述】:

我想在扩展名之前在文件名中添加一些文本。示例:name.ext >>> name_su.ext.
我可以使用传统的 python 字符串格式来做到这一点:

filename = 'name.ext'
suffix = '_su'
print("{0}{2}{1}".format(*os.path.splitext(filename) + (suffix, )))
# This will print: name_su.ext

我想知道是否可以在一行中使用 f 字符串表示法实现相同的效果,而无需两次调用 os.path.splitext(filename)

【问题讨论】:

  • FWIW,你甚至不需要插值。 suffix.join(os.path.splitext(filename))
  • 看看this问题。

标签: python f-string


【解决方案1】:

调用os.path.splitext() 两次可能是可以避免的,但它快速且易读:

print(f'{os.path.splitext(filename)[0] + suffix + os.path.splitext(filename)[1]}')

【讨论】:

  • 谢谢你,@AlexM。我正在寻找一种无需调用两次os.path.splitext() 的方法。
  • 为什么还要费心使用 f 弦? print(os.path.splitext(filename)[0] + suffix + os.path.splitext(filename)[1])
  • 另外,没有必要调用它两次,就像我在这个问题上评论的那样:suffix.join(os.path.splitext(filename))。所以如果你需要一个 f 字符串,print(f'{suffix.join(os.path.splitext(filename))}')
猜你喜欢
  • 2014-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-24
  • 2011-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多