I am trying to extract certain part of some strings. These strings look like
a = "1_2_3"
b = "1_2_3_4"
I would want to get everything of each string before the last underscore so:
"1_2"
"1_2_3"
I thought this line should work:
"_".join(a.split("_")[:-1])
"_".join(b.split("_")[:-1])
but it gives me the error: AttributeError: 'str' object has no attribute 'joint'
However, apparently, a.split("_")[:-1]
is not a str but a list (I checked by type(a.split("_")[:-1])
). Does anyone know why this happens and how to solve it?
CodePudding user response:
Sounds like you misspelled using str.join()
as str.joint()
.
For your usecase though, looks like str.rpartition() would fit better, removing the split-join loop.
a = "1_2_3"
b = "1_2_3_4"
print(a.rpartition("_")[0])
print(b.rpartition("_")[0])
Output
1_2
1_2_3
CodePudding user response:
You got a good answer that addresses your problem that you should probably accept. But in case you want an alternative, you can make a slice of the string directly:
a = "1_2_3"
b = "1_2_3_4"
a[:a.rindex('_')]
# '1_2'
b[:b.rindex('_')]
# '1_2_3'
This works by finding the right-most index of _
in the string and slicing to that point.
CodePudding user response:
Or you could try rsplit
:
>>> a = "1_2_3"
>>> x, _ = a.rsplit('_', 1)
>>> x
'1_2'
>>>
Or one with regex:
>>> import re
>>> a = "1_2_3"
>>> re.sub('_\d$', '', a)
'1_2'
>>>