只从字符串中删除一个字符一次 python 3
Only removing a character one time from a string python 3
如何从字符串中删除一个字符,但只删除一次?这是我的例子:
string = "/file/file/file.jpg"
string = string.replace("/","")
这将从我的字符串中删除所有 "/"
,但我只想删除第一个;我怎样才能做到这一点?
一般来说:str.replace()
需要第三个参数,计数:
string.replace('/', '', 1)
来自str.replace()
documentation:
str.replace(old, new[, count])
[...] If the optional argument count is given, only the first count occurrences are replaced.
在您的特定情况下,您可以只使用 str.lstrip()
method 来从开头删除斜线:
string.lstrip('/')
这是微妙的不同;它将从一开始就删除 零个或多个 这样的斜线,其他任何地方都不会。
演示:
>>> string = "/file/file/file.jpg"
>>> string.replace('/', '', 1)
'file/file/file.jpg'
>>> string.lstrip('/')
'file/file/file.jpg'
如何从字符串中删除一个字符,但只删除一次?这是我的例子:
string = "/file/file/file.jpg"
string = string.replace("/","")
这将从我的字符串中删除所有 "/"
,但我只想删除第一个;我怎样才能做到这一点?
一般来说:str.replace()
需要第三个参数,计数:
string.replace('/', '', 1)
来自str.replace()
documentation:
str.replace(old, new[, count])
[...] If the optional argument count is given, only the first count occurrences are replaced.
在您的特定情况下,您可以只使用 str.lstrip()
method 来从开头删除斜线:
string.lstrip('/')
这是微妙的不同;它将从一开始就删除 零个或多个 这样的斜线,其他任何地方都不会。
演示:
>>> string = "/file/file/file.jpg"
>>> string.replace('/', '', 1)
'file/file/file.jpg'
>>> string.lstrip('/')
'file/file/file.jpg'