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
CodePudding user response:
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'
CodePudding user response:
You can use list slicing and str.join
in case _
is in the string, and you can just get the first element of the split (which is the only element) in the other case:
sp = string.split('_')
result = '_'.join(sp[1:]) if len(sp) > 1 else sp[0]
CodePudding user response:
All of the ways are good but there is a very simple and optimum way for this.
Try:
s = 'aaabbnkkjbg_gghjkk_ttty'
try:
ans = s[s.index('_'):]
except:
ans = s
CodePudding user response:
Ok so your error is supposed to happen/expected because you are using '_'
as your delimiter and it doesn't contain it.
See How to check a string for specific characters? for character checking.
If you want to only split iff the string contains a '_'
and only on the first one,
input_string = "blah_end"
delimiter = '_'
if delimiter in input_string:
result = input_string.split("_", 1)[1] # The ",1" says only split once
else:
# Do whatever here. If you want a space, " " to be a delimiter too you can try that.
result = input_string
CodePudding user response:
this code will solve your problem
txt = "apple_banana_cherry_orange"
# setting the maxsplit parameter to 1, will return a list with 2 elements!
x = txt.split("_", 1)
print(x[-1])