【问题标题】:Trim string till any specified character [duplicate]修剪字符串直到任何指定的字符[重复]
【发布时间】:2026-01-25 04:05:01
【问题描述】:

需要泛化解决方案 我有一个字符串,想删除冒号前的所有字符 (:)。像这样:

oldstring = 'Resolution: 1366 x 768'
newstring = '1366 x 768'

【问题讨论】:

  • 试试newstring = oldstring.replace('Resolution: ', '')
  • 我需要所有字符串的通用解决方案
  • 是否还要删除冒号后的所有空格?
  • 如果输入是“纵横比:16:9”,预期的输出是什么?
  • 如果 : 之前的内容不同,则只需 newstring = oldstring.split(':')[1].strip()

标签: python string colon


【解决方案1】:

你可以使用:

newstring = oldstring.split(':')[-1].strip()

你的例子:

newstring, _ = oldstring.split(':')
newstring = newstring.strip()

【讨论】:

  • 如果冒号不止一个,也传递可选的maxsplit arg 会更安全。
  • 如果 OP 提供更多信息会更“安全”,所以我可以假设所有字符串都有 1 个冒号
  • @JohnGordon thx 建议
【解决方案2】:

你可以使用

newstring = oldstring[oldstring.find(":") + 1:]

它将删除第一个 : 之前的所有内容。

要删除最后一个 : 之前的所有内容,请改用它:

newstring = oldstring[oldstring.rfind(":") + 1:]

如果要删除: 后面的空格,请添加strip()

newstring = oldstring[oldstring.find(":") + 1:].strip()

如果字符串中没有:,这段代码不会抛出异常,它根本不会删除任何东西。如果你想有一个异常来处理它,你应该使用

newstring = oldstring[oldstring.index(":") + 1:]

newstring = oldstring[oldstring.rindex(":") + 1:]

【讨论】:

    【解决方案3】:

    这也是一种选择:

    newstring = oldstring[oldstring.find(':') + 1:]
    

    【讨论】:

    • 我已经回答过了
    • 你说得对,我没看到。