修剪字符串直到任何指定字符

2024-09-28 22:21:36 发布

您现在位置:Python中文网/ 问答频道 /正文

需要推广解决方案吗 我有一个字符串,希望删除冒号(:)之前的所有字符。像这样:

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

Tags: 字符串解决方案字符resolution冒号newstringoldstring
3条回答

这也是一种选择:

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

你可以用

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:]

您可以使用:

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

例如:

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

相关问题 更多 >