python - 如果存在字符则拆分字符串,否则不拆分

标签 python python-3.x

我在 python 中有一个 string 如下所示

testing_abc

我想根据_拆分字符串并提取2元素

我做了如下

split_string = string.split('_')[1]

我得到了预期的正确输出

abc

现在我希望它适用于以下字符串

1) xyz

当我使用

split_string = string.split('_')[1]

我得到以下错误

list index out of range

我想要的预期输出是 xyz

2) testing_abc_bbc

当我使用

split_string = string.split('_')[1]

我得到 abc 作为输出

我想要的预期输出是 abc_bbc

基本上我想要的是

1) If string contains `_` then print everything after the first `_` as variable
2) If string doesn't contain `_` then print the string as variable

我怎样才能实现我想要的

最佳答案

splitmaxsplit 参数设置为 1,然后取出结果列表的最后一个元素。

>>> "testing_abc".split("_", 1)[-1]
'abc'
>>> "xyz".split("_", 1)[-1]
'xyz'
>>> "testing_abc_bbc".split("_", 1)[-1]
'abc_bbc'

关于python - 如果存在字符则拆分字符串,否则不拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73057180/

相关文章:

python - 将内置函数类型转换为方法类型(在 Python 3 中)

python - 子弹没有出现在简单的太空入侵者游戏中

python-3.x - 协程的 Python 回溯

python - 显示在列中的嵌套列表

python - 调整 R 中热图的颜色和比例

python - PIL - 从 JPG 和 PNG 框架制作 1 个 PNG

python - 如何获取第一个span标签?

python - 多处理池 : How to call an arbitrary list of methods on a list of class objects

python - Adobe Acrobat DC 和 Python 自动化

python - 在 Python Shell 中打印当前行