我在 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
我怎样才能实现我想要的
最佳答案
将 split
的 maxsplit
参数设置为 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/