我有一个string喜欢下面的python
testing_abc
Run Code Online (Sandbox Code Playgroud)
我想根据元素分割字符串_并提取2元素
我已经做了如下
split_string = string.split('_')[1]
Run Code Online (Sandbox Code Playgroud)
我得到了预期的正确输出
abc
Run Code Online (Sandbox Code Playgroud)
现在我希望它适用于以下字符串
1) xyz
Run Code Online (Sandbox Code Playgroud)
当我使用
split_string = string.split('_')[1]
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
list index out of range
Run Code Online (Sandbox Code Playgroud)
我想要的预期输出是xyz
2) testing_abc_bbc
Run Code Online (Sandbox Code Playgroud)
当我使用
split_string = string.split('_')[1]
Run Code Online (Sandbox Code Playgroud)
我得到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
Run Code Online (Sandbox Code Playgroud)
我怎样才能实现我想要的
小智 9
设置tomaxsplit的参数,然后获取结果列表的最后一个元素。split1
>>> "testing_abc".split("_", 1)[-1]
'abc'
>>> "xyz".split("_", 1)[-1]
'xyz'
>>> "testing_abc_bbc".split("_", 1)[-1]
'abc_bbc'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1955 次 |
| 最近记录: |