首页 > 解决方案 > Python Strip 不删除字符

问题描述

我正在尝试从照片 URL 中删除一些不需要的字符。

相关代码:

for img in imgSrc:
    print(img)
    img.strip('US40')
    print(img)

没有抛出错误,但两个打印语句的输出相同:

https://images-na.ssl-images-amazon.com/images/I/51uUvUZNoUL._AC_US40_.jpg
https://images-na.ssl-images-amazon.com/images/I/51uUvUZNoUL._AC_US40_.jpg
https://images-na.ssl-images-amazon.com/images/I/51GQJaFyk1L._AC_US40_.jpg
https://images-na.ssl-images-amazon.com/images/I/51GQJaFyk1L._AC_US40_.jpg

标签: python

解决方案


strip 仅适用于前导和尾随字符。在这种情况下,您应该使用替换

剥离: S.strip([chars]) -> str

返回删除了前导和尾随空格的字符串 S 的副本。如果给出了 chars 而不是 None,则改为删除 chars 中的字符。

替换: S.replace(old, new[, count]) -> str

返回 S 的副本,其中所有出现的子字符串 old 都替换为 new。如果给定了可选参数 count,则仅替换第一个 count 出现。

for img in imgSrc:
    print(img)
    img = img.replace('US40',"")
    print(img)

推荐阅读