简体   繁体   English

在Python中某些字符后获取子字符串

[英]Getting Substring after certain char in python

I want to cut a String such as "0011165.jpg_Fish" to get only Fish, so everything after the "_", how do i do that in python? 我想剪切诸如“ 0011165.jpg_Fish”之类的字符串以仅获取Fish,因此“ _”之后的所有内容,我该如何在python中做到这一点?

Thank you very much! 非常感谢你!

Please use str.partition instead of str.split . 请使用str.partition而不是str.split This is robust, since you can always expect 3 items, unlike, split which maybe tricky to handle if the input string doesn't have the split character , 这是可靠的,因为您总是可以预期3项目,与split不同,如果input string不包含split character ,可能很难处理。

>>> word = '0011165.jpg_Fish'
>>> not_required, split_char, required = word.partition('_')
>>> required
'Fish'

Try 尝试

"0011165.jpg_Fish".split("_")[1]

And in case of a Dataframe 如果是数据框

train['Label'] = train.Image_Labels.str.split("_").str[1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM