Search code examples
pythonlistends-with

Use endswith() to check if a string in one list ends with a string from another list?


I need to check if items within a list is listed at the end of a string in another list, preferably by using endswith() somehow but I'm not really sure how to solve it with just this method and not let it depend on length of the other list etc..

For a single list this works perfectly fine:

mylist = ["item 1 a", "item 2 a", "item 3 b"]

for item in mylist:
    if item.endswith("a"):
        print(f"{item} ends with 'a'")
    else:
        print(f"{item} ends with 'b'")

# Output: 
# item 1 a ends with 'a'
# item 2 a ends with 'a'
# item 3 b ends with 'b'

But let's say I have 2 lists instead, I'm not sure how to check if a listitem in one list ends with one of the options from another list. Since endswith() just returns True or False, I'm fully aware of the code below being wrong, but it's more a way of showing how I want it to work:

mylist = ["item 1", "item 2", "item 3"]
newlist = ["added item 1", "added item 3"]

for item in mylist:
    if item.endswith(item) in newlist:
# Wont work because the return is a boolean
# value, just an example of what I'm looking for'
        print(f"newlist has {item} added")
    else:
        print(f"newlist still waiting for {item}")

I know there are other ways to get the same result but is there any way to do this without the need for using regular expressions or yet another list to store the different strings to and just base it on endswith()?


Solution

  • If I understood you correctly this should be the solution

    mylist = ["item 1", "item 2", "item 3"]
    newlist = ["added item 1", "added item 3"]
    
    for item in mylist:
        for other_item in newlist:
            if other_item.endswith(item):
                print(f"newlist has {item} added")
                break
            
            print(f"newlist still waiting for {item}")
    

    Console output is this

    newlist has item 1 added
    newlist still waiting for item 2
    newlist still waiting for item 2
    newlist still waiting for item 3
    newlist has item 3 added
    

    If you don't want the output for item 2 to be duplicate you can just add a variable where you store if the second for loop found the item and if not you can write that message. Something like:

    mylist = ["item 1", "item 2", "item 3"]
    newlist = ["added item 1", "added item 3"]
    
    for item in mylist:
        found = False
        for other_item in newlist:
            if other_item.endswith(item):
                print(f"newlist has {item} added")
                found = True
                break
    
        if found is not True:
            print(f"newlist still waiting for {item}")
    

    Which gets you just:

    newlist has item 1 added
    newlist still waiting for item 2
    newlist has item 3 added