Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string if character is present else don't split

I have a string like below in python

testing_abc

I want to split string based on _ and extract the 2 element

I have done like below

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

I am getting the correct output as expected

abc

Now I want this to work for below strings

1) xyz

When I use

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

I get below error

list index out of range

expected output I want is xyz

2) testing_abc_bbc

When I use

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

I get abc as output

expected output I want is abc_bbc

Basically What I want is

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

How can I achieve what I want

like image 657
nmr Avatar asked Sep 12 '25 06:09

nmr


1 Answers

Set the maxsplit argument of split to 1 and then take the last element of the resulting list.

>>> "testing_abc".split("_", 1)[-1]
'abc'
>>> "xyz".split("_", 1)[-1]
'xyz'
>>> "testing_abc_bbc".split("_", 1)[-1]
'abc_bbc'
like image 180
fsimonjetz Avatar answered Sep 13 '25 18:09

fsimonjetz