Avatar ·

How to trim a string in python to a desired character from the end

📁 строка, python, работа

Given a string:

a = 'First - second - third'

How can I trim the string from the end to ' -' to get:

'First - second'

Previously, when the string contained only one ' - ', I did it via .split(' - ') and removed the last element at index [1], but as soon as strings with two ' - ' appeared, it stopped working correctly. Or maybe I can also use .split(' - '), but remove not specifically [1], but simply the last element in the resulting list. Does anyone know how to do this? Please advise.

Avatar ·

Study list comprehensions, they are very often useful in Python, as they allow you to make selections quite concisely and clearly:

mydict = {'main':'open','second':'close','third':'open'}print([k for k in mydict if mydict[k] == ""open""])

Output:

['main', 'third']

Essentially, this is the same solution from another answer, only written in one line and without using

Log in to leave an answer

Blogs