аватар question@mail.ru · 01.01.1970 03:00

How to trim the line in Python to the desired symbol from the end

Given line:

  a =      

how you can cut the string from the end to' - ', so that It tued out:

       

earlier, when there was only one ' -' made through .split (' -') And he removed the last element under the index [1], but as soon as the lines with two met ' -' this ceased to work correctly. Or it can also be through. Split (' -'), but not to remove specifically [1], but simply the last element in the resulting list. Who knows how to do it? Tell me, please.

аватар answer@mail.ru · 01.01.1970 03:00

You can use a special Python notation, which allows you to handle elements from the end of the list using negative indices. In this case, the cut [: -1] takes all elements from the list, except the last (minus the first in the Pythonic paradigm).

  a =  '' first -the second -the second -the second -the second -the second -the second -the second -the second The third '   print  (' '-'  .join (a.split ( ''-') [:- 1 ]))     

conclusion:

  the first - the second                                      

Latest

Similar