-1

I'm trying to write a function that uses a checker that could be any length and checks it against the list. It should be case insensitive when checking and print the word. Example below

Input= startsWith('a',['apple','ApPle','orange','Apple','kiwi','apricot'])

Output:

apple
ApPle 
Apple 
apricot

But, it prints every string in the list all in lower case.

def startsWith(checker,lister):

    checker.lower()
    size = len(lister)
    i=0
    checklength = len(checker)
    lister = [element.lower() for element in lister]
    while(i<size):
        checkinlist = lister[i]
        if(checkinlist[0:checklength-1] in checker):
            # this is just to test to see if the variables are what i need
            # once the if statement works just append them to a new list
            # and print that
            print(lister[i])

        i=i+1
Anil_M
  • 10,893
  • 6
  • 47
  • 74

3 Answers3

1

Here's the root of the problem

lister = [element.lower() for element in lister]

lister now only contains lowercase strings, which you then print. You need to delay the lower() until you check for checker.


No need to check the length of anything. You can use filter

def startsWith(checker, lister):
    return list(filter(lambda x: x.lower().startswith(checker.lower()), lister))

for x in startsWith('a',['apple','ApPle','orange','Apple','kiwi','apricot']):
    print(x)

Output

apple
ApPle
Apple
apricot
Community
  • 1
  • 1
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0
def startsWith(checker,lister):

    for i in range(len(lister)):
        words = lister[i].lower()
        if(words.startswith(checker)):
            print(lister[i])

def main():
    startsWith('a',['apple','ApPle','orange','Apple','kiwi','apricot'])
main()

OUTPUT

apple
ApPle
Apple
apricot
>>> 
Maddy
  • 2,025
  • 5
  • 26
  • 59
0

You should not mutate the original elements of lister, rather do the comparison on a new copy of those elements that has been converted to lower case.

It can be done in a single list comprehension.

def startsWith(checker, lister):
    cl = checker.lower()
    return [s for s in lister if s.lower().startswith(cl)]

Input= startsWith('a',['apple','ApPle','orange','Apple','kiwi','apricot'])

for i in Input:
    print(i)

Output:

apple
ApPle
Apple
apricot
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61