【问题标题】:AttributeError: 'tuple' object has no attribute 'replace' For bracketsAttributeError: 'tuple' 对象没有属性 'replace' 对于括号
【发布时间】:2020-01-12 14:35:24
【问题描述】:

我有一个简单的代码尝试通过替换一些字符来重命名名称文件,但我收到了这个错误:

name=name.replace=(")","")
AttributeError: 'tuple' object has no attribute 'replace'

代码在这里:

import os
os.chdir("/home/ubuntu/Desktop")
nfiles=os.listdir(os.getcwd())
new_files = [nfile for nfile in nfiles if nfile[-4:].lower()=='.txt']

for file in new_files:

    name = file
    name=name.replace=(")","")
    name=name.replace=(",","_")
    print(name)

【问题讨论】:

  • 不,new_files 包含扩展名为 .txt 的文件名

标签: python python-3.x string replace


【解决方案1】:

replace 是一个可以应用于字符串的方法,所以你应该这样称呼它replace('old_str', 'new_str')。您没有正确使用替换,因此请改用它:

name=name.replace(")","")
name=name.replace(",","_")

【讨论】:

  • 同样的事情。有什么不同?
  • 不一样,你看,你有name=name.replace=(")",""),而你应该使用name=name.replace(")","")。您正在添加一个额外的=
  • @SAFAK,我添加了 Python 官方文档的链接,以便您查看替换的使用。
猜你喜欢
  • 2021-03-18
  • 1970-01-01
  • 2023-01-26
  • 2014-09-02
  • 2019-09-12
  • 2014-06-19
  • 1970-01-01
  • 1970-01-01
  • 2015-06-22
相关资源
最近更新 更多