简体   繁体   中英

strings match after a certain character

I wanted to see if two strings matched each other after the last time a certain character appears. For example:

same_list = ['Time - is an illusion.', 'Lunchtime - which is delicious - is an illusion.']

True

So in this case my certain character is '-'. I want to see if the string after the last '-' for both strings match each other. The string after '-' is 'is an illusion.' for both strings. Therefore it is true.

So far I have:

same_list = ['Time - is an illusion.', 'Lunchtime - which is delicious - is an illusion.']

some_list = []

for string in same_list:
    for ch in string:
        if ch == '-':
            new_string = string.split(ch)
            some_list.append(new_string)

i = 0

for sublist[-1] in some_list:

I feel like I'm forgetting an easier way of doing this in python. All I can remember is the while loop, but that would return the first occurrence of '-', not the last. Also, the function I have written returns the second string twice as it was split twice. How do I get rid of that?

You can do something simple like this (assuming that all endings in a list must match):

def end_matches(*phrases):           # phrases becomes a tuple that will take any number
    phrase_endings = set()           # number of positional parameters
    for phrase in phrases:
        end = phrase.split('-')[-1]  # take the last element of the split list
        phrase_endings.add(end)
    return len(phrase_endings) == 1  # the set holds only unique values, so a set of
                                     # length 1 means all values in the set are the same

You can now test it out:

>>> same_list = ['Time - is an illusion.', 'Lunchtime - which is delicious - is an illusion.']
>>> end_matches(*same_list)          # unpack the list into individual positional arguments
True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM