在Python中使用两个替换

2024-10-02 04:22:42 发布

您现在位置: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的方法是什么?你知道吗


Tags: inimportreenvnewstringbinos
3条回答

您正在对^{}(返回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类型本身上可用的等效方法。你知道吗

我对python也很陌生,但我的猜测是要改变这一行:

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

分为:

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

相关问题 更多 >

    热门问题