Python:尝试使用带有.format()的“{} .replace()”

时间:2016-04-04 15:02:05

标签: python python-2.7

一个相当简单的问题,但对于我的生活,我无法理解......

我有以下代码:

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))

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

有人可以指出我正确的方向寻找资源来帮助解决这个问题吗?

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

由于

4 个答案:

答案 0 :(得分:3)

您不应该将python字符串操作TypeError: undefined is not an object (evaluating 'current.$$route.title') in C:/front/app/scripts/app.js (line 9) C:/front/app/scripts/app.js:9:14402 $broadcast@C:/front/bower_components/angular/angular.js:17348:33 C:/front/bower_components/angular-route/angular-route.js:647:36 processQueue@C:/front/bower_components/angular/angular.js:15757:30 C:/front/bower_components/angular/angular.js:15773:39 $eval@C:/front/bower_components/angular/angular.js:17025:28 $digest@C:/front/bower_components/angular/angular.js:16841:36 flush@C:/front/bower_components/angular-mocks/angular-mocks.js:1779:45 C:/front/test/unit/factories/user-factory-spec.js:86:22 format()的参数混合。

replace()

答案 1 :(得分:2)

what are you need to do is

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

or more readable

newName = "{rmvFileFormat}_{time}_{addFileFormat}".format(rmvFileFormat = FileName.replace(".png",""), 
                                                          time = time_stamp.replace(":","-").replace("","_"),
                                                          addFileFormat = name_string+".png")
os.rename(FileName, newName)

答案 2 :(得分:1)

您正在使用的格式的基本形式是:

"Hello {}".format("there")

评估她的字符串"你好"。在其简单形式中,字符串中的每个{}将按顺序替换为format中的字符串。更多详细信息,您可以在这里找到: https://pyformat.info/

答案 3 :(得分:0)

replace是一种字符串方法,您无法在要格式化的字符串中使用它。你必须这样做:

s = "A {} string".format('very nice'.replace(' ', '_'))

如果您只想在变量中进行替换(这似乎是您的目标),或者:

s = "A {} string".format('very nice').replace(' ', '_')

如果您想全局更换。

关于更好的方法,我会使用os.path.splitext拆分扩展,以正确的格式生成时间戳(当然,如果你可以控制它),而不是使用替换,和在os.rename部分之前完成所有替换,因此它更具可读性(即将正确的字符串存储在变量中并使用format中的字符串,而不是在一行中完成所有操作)