在 Python 中使用两个替换

Using two replaces in Python

我是 Python 的新手,我意识到我无法像 JavaScript:

那样连接 replace
#!/usr/bin/env python
import os
import re
import string

for filename in os.listdir("."):
  if filename.endswith(".png"):
    new_filename = string.replace(filename, "2x", "@3x").replace(filename, "-lanczos3", "")

    os.rename(filename, new_filename)

我收到这个错误:

File "hello.py", line 8, in <module>
    new_filename = string.replace(filename, "2x", "@3x").replace(filename, "-lanczos3", "")
TypeError: an integer is required

Python 方法是什么?

filename.replace("2x", "@3x").replace("-lanczos3", "")

filename 上致电 replace。像这样:

filename = "abcd"
filename.replace("a", "b").replace("c", "d")

这个returns

'bbdd'

我也是 python 的新手,但我的猜测是更改此行:

new_filename = string.replace(filename, "2x", "@3x").(filename, "-lanczos3", "")

进入:

new_filename = filename.replace("2x", "@3x").replace("-lanczos3", "")

您正在调用 str.replace() (a method) on the return value of string.replace()(返回 str 对象的函数)。

只需使用方法:

new_filename = filename.replace("2x", "@3x").replace("-lanczos3", "")

您的错误源于 str.replace() 的第三个参数,它必须是限制替换次数的整数。你基本上是这样做的:

'somestring'.replace(thingto_replace, "-lanczos3", "")

其中 "" 参数不是整数。

可以string.replace()做同样的事情,但是你必须将一个调用的结果作为另一个调用的第一个参数传递:

new_filename = string.replace(string.replace(filename, "2x", "@3x"), "-lanczos3", "")

想要这样做,因为 string 功能已被弃用;请参阅 documentation:

The following list of functions are also defined as methods of string and Unicode objects; see section String Methods for more information on those. You should consider these functions as deprecated, although they will not be removed until Python 3.

该部分中的任何函数都具有可直接用于 str 类型本身的等效方法。