【问题标题】:strange results with .strip .lstrip including a slash ( '/' ) [duplicate].strip .lstrip 的奇怪结果包括斜杠('/')[重复]
【发布时间】: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

标签: python strip


【解决方案1】:

strip 接受要删除的字符的列表/可迭代,而不是字符串。

在此请求删除a两端的所有/get

使用split 代替: a.rsplit('/')[-1] 或专用库来解析/处理路径。

【讨论】:

  • @peets 你也可以使用replace字符串方法,使用count为1
猜你喜欢
  • 2018-08-01
  • 1970-01-01
  • 2011-08-30
  • 1970-01-01
  • 2011-08-04
  • 2011-04-22
  • 2012-08-18
  • 2020-10-22
  • 2015-04-14
相关资源
最近更新 更多