gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:28:55 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com