我在 python 中有一个 str,如下所示。我想从中提取一个子字符串。
table='abc_test_01'
number=table.split("_")[1]
结果我得到了 test。
我想要的是第一个 _ 之后的所有内容。
我想要的结果是 test_01 我该如何实现。
请您参考如下方法:
这是许多人已经给出的代码
table='abc_test_01'
number=table.split("_",1)[1]
但是当出现不在字符串中时,上面的方法可能会失败,然后你会得到 IndexError: list index out of range
例如。
table='abctest01'
number=table.split("_",1)[1]
上面的代码会抛出 IndexError,因为它不在字符串中
所以处理这个问题的更准确的代码是
table.split("_",1)[-1]
因此 -1 不会受到任何伤害,因为出现的次数已经设置为一次。
希望对您有所帮助:)
