【发布时间】:2021-12-24 12:57:56
【问题描述】:
(在 Ubuntu Linux 20.4 64Bit 上使用 python 3.8 的示例):
>>> a="/get/todo.dat"
>>> b="/get/"
>>> a.lstrip(b)
'odo.dat'
expected:
'todo.dat'
更糟糕的是:
expected answer in each case:
'0018.dat'
# first test of lstrip()
>>> name='data/rwl3_v001_Data0018.dat'
>>> mask='data/rwl3_v001_Data'
>>> name.lstrip(mask)
'8.dat'
# strip() should return the same answer:
>>> name.strip(mask)
'8.'
虽然 '/t' 可能被误解为 tab '\t' (?) 第二个例子更让我困惑。
任何想法会发生什么?帮助表示赞赏。我当然可以写一个函数,但是关于strings和strip有什么要了解的吗?
【问题讨论】:
-
strip接受要删除的字符列表/可迭代,不是字符串 -
strip删除所有出现的提供的可迭代对象。 -
你可以使用正则表达式或
find字符串方法 -
使用正则表达式的可行解决方案:
re.sub('^' + re.escape(mask), '', name)用于 lstrip,re.sub(re.escape(mask) + '$', '', name)用于 rstrip -
下次,首先检查您正在使用的documentation on the method,在这种情况下,它恰好建议您尝试执行的操作是the correct function。