【问题标题】:How to strip a certain string from each the list items如何从每个列表项中删除某个字符串
【发布时间】:2017-07-04 14:00:15
【问题描述】:

我将C:\ 中的文件路径list 存储在一个名为filepaths 的列表中,现在我必须在执行for 循环时从所有filepaths 中删除C:\

循环时我无法找到 strip 方法,因为每个元素都以类型 list 的形式出现。请在下面找到我的代码。

filepaths = ['C:\folder\file1.jpg','C:\file2.png','C:\file3.xls']
tobestriped = 'C:\'
for filepath in filepaths:
    newfilepath = filepath.strip(tobestriped)
    print(newfilepath)

【问题讨论】:

    标签: list python-3.x loops strip


    【解决方案1】:

    首先,在tobestriped 中,您将收到一个错误,因为\' 将被转义。你可以使用tobestriped = 'C:\\'

    来自this所以回答:

    “原始字符串文字”是一种稍微不同的字符串语法 字面量,其中反斜杠 \ 表示“只是一个 反斜杠”(除非它出现在引号之前 否则终止文字)——没有“转义序列”来表示 换行符、制表符、退格键、换页符等等。在普通字符串中 文字,每个反斜杠必须加倍以避免被视为 转义序列的开始。

    接下来,在您的路径列表中\f 也将被转义。要解决这个问题,请将这些字符串设为原始字符串:

    filepaths = [r'C:\folder\file1.jpg', r'C:\file2.png', r'C:\file3.xls']
    

    你会得到想要的结果:

    filepaths = [r'C:\folder\file1.jpg', r'C:\file2.png', r'C:\file3.xls']
    tobestriped = 'C:\\'
    
    for filepath in filepaths:
        newfilepath = filepath.strip(tobestriped)
        print(newfilepath)
    

    输出:

    folder\file1.jpg
    file2.png
    file3.xls
    

    您的解决方案的替代方案是利用所有字符串以 C:\ 开头的事实,因此您可以执行以下操作:

    print([x[3:] for x in filepaths])
    

    【讨论】:

    • 我无法做到newfilepath = filepath.strip(tobestriped),正如您在回答中提到的那样。我收到了这个错误,AttributeError: 'list' object has no attribute 'strip'
    • 使用您提供的数据,我的每个解决方案都有效。如果您的路径以列表的形式出现,那么就在 for 循环之前:flat_list = [item for sublist in l for item in sublist]
    • 如果我正在读取一个 csv 文件并制作我的 filepaths 列表,这种方法有什么不同吗?
    • 我们不要把这变成一个永无止境的故事。发布所有相关代码以及数据的实际外观
    猜你喜欢
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多