Bubbles
Bubbles

Reputation: 81

How to cut a phrase in half in python

I have a phrase that needs to be cut in half (only first half will be used). I would only like to use the half of the line. Here is my code,

 def license_trial_card(self):
    card = self.driver.find_element(*Elements._License_card_text)
    cardtext = card.text
    split = cardtext.split(' ', 4)
    return split

The output I am getting is,

['Your', 'Trial', 'is', 'valid', 'until 24/08/2017 14:06.']

I only need to use the part 'Your Trial is valid until'. The rest of the phrase will not be used for verification as the date/time will be different every time.

Can anyone help?

Upvotes: 0

Views: 543

Answers (2)

Rick
Rick

Reputation: 45291

This sounds like it's a phrase that will be reused a lot without changing. I suggest entering the text as a class property with a format specification at the end. The format specification could be populated by a stored date string.

One way to do all of that (and to make sure you don't accidentally overwrite the text) would be:

class Mine(): 
    _validuntil = 'Your Trial is valid until {}'
    def __init__(self):
        self._valid_date = get_the_cuttoff_date_text()
    @property
    def validuntil(self):
        return self._validuntil.format(self.valid_date)
    @property
    def valid_date(self):
        return self._valid_date

Assuming your get_the_cuttoff_date_text() function (during the object initialization phase) provides the correct string, now you can just do:

print(my_object.validuntil)

Upvotes: 0

asiviero
asiviero

Reputation: 1235

Just join the var without the last element, and change 4 for 5 to get the "until" as well:

 def license_trial_card(self):
    card = self.driver.find_element(*Elements._License_card_text)
    cardtext = card.text
    split = cardtext.split(' ', 5)
    joined = ' '.join(split[:-1])
    return joined

Upvotes: 2

Related Questions