如何从字符串中删除字符,但只能删除一次?这是我的示例:
string = "/file/file/file.jpg"
string = string.replace("/","")
这将从我的字符串中删除所有
"/"
,但是我只希望它删除第一个。我该如何做到这一点? 最佳答案
通常,str.replace()
带有第三个参数,计数:
string.replace('/', '', 1)
从
str.replace()
documentation:str.replace(old, new[, count])
[...]如果给出了可选的参数计数,则仅替换第一个出现的计数。
在您的特定情况下,您可以只使用
str.lstrip()
method从一开始就删除斜杠:string.lstrip('/')
这是微妙的不同。它将从一开始就删除零个或多个这样的斜杠,并且没有其他地方。
演示:
>>> string = "/file/file/file.jpg"
>>> string.replace('/', '', 1)
'file/file/file.jpg'
>>> string.lstrip('/')
'file/file/file.jpg'
关于python - 仅从字符串python 3中删除一次字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28611816/