Skip to main content
 首页 » 编程设计

Python:尝试将 "{}.replace()"与 .format() 一起使用

2025年05月04日17kenshinobiy

一个相当简单的问题,但对于我的生活我无法弄清楚...

我有以下代码:

os.rename(FileName, FileName.replace(".png","")+"_"+time_stamp.replace(":","-").replace(" ","_")+"_"+name_string+".png") 

基本上是重命名图像文件。

我想使用 .format() 结构,但我不知道如何让 .replace() 函数使用它。

目前我转换后的代码如下所示:

os.rename(FileName, "{}.replace(".png","")_{}.replace(":","-").replace(" ","_")_{}.png".format(FileName,time_stamp,name_string)) 

目前给出的错误是第一次替换时的“语法无效”(在“”中的插入符号(“.png”,“”))。

有人可以为我指明正确的方向以获得资源来帮助解决这个问题吗?

有没有更好的方法来做我想做的事情?

谢谢

请您参考如下方法:

您不应该将 python 字符串操作 replace() 与 format() 的参数混合使用.

os.rename(FileName, '{0}_{1}_{2}.png'.format( 
    FileName.replace(".png", ""), 
    time_stamp.replace(":", "-"), 
    name_string.replace(" ", "_") 
))