a = 'first - second - third'
How can you trim the string from the end to ‘-‘ to work:
'first - second'
Previously, when only one ‘-‘ was met in the line, I did through .split (‘-‘) and removed the last element under the index , but as soon as the rows met with two ‘-‘ it stopped working correctly. Or can also via .split (‘-‘), but not specifically deleted , but just the last item in the list received. Who knows how to do? Tell me, please.
Answer 1, Authority 100%
You can use a special python notation, which allows you to handle the elements from the end of the list using negative indices.
In this case, the slice [: -1] takes all elements from the list, except for the latter (minus the first in the Python paradigm).
a = 'first - second - third' Print ('-'. Join (A.Split ('-') [: - 1]))
first – second
Answer 2, AUTHORITY 78%
a = 'first - second - third' # Smash the string along the right '-', take the left side B = A.Rpartition ('-')  Print (b) # first - second
Partitionbreaks the string into three parts: all that is left of
separator, separator itself, the fact that on the right of the separator.
If the separator is not found, the source line and two empty strings are returned. Those. In any case, a consignment of 3 elements is returned, so additional checks for the presence of a separator or the length of the result (as using
Str.split ()) are not needed.
rpartitionDoes the same, but breaks through the rightmost separator. If the separator is not found, then two empty strings and source string return.
Answer 3, Authority 33%
Option via the search method from the end str.rfind and row slice:
a = 'first - second - third' i = a.rfind ('-') IF i! = -1: A = A [: i] Print (A) # First second
str.rfind return index, but if No found
-1 , so you need check.