Home python How to trim a string in Python to the desired symbol from...

How to trim a string in Python to the desired symbol from the end




Dana Row:

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 [1], but as soon as the rows met with two ‘-‘ it stopped working correctly. Or can also via .split (‘-‘), but not specifically deleted [1], 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 ('-') [0]
Print (b) # first - second
  • Partition breaks 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.

  • rpartition Does 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.

Previous articleCode Decryption
Next articleRacked array

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions