I'm trying to run a loop through a dir(androidhelper.Android) to find everything that starts with m and then lists it. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

I'm trying to run a loop through a dir(androidhelper.Android) to find everything that starts with m and then lists it.

This sounds simple enough but I couldnt figure it out. There are like 5 items in the dir(androidhelper.Android) that start with the letter "m". I just want to do this for practice. What I've tried: import androidhelper droid = androidhelper.Android direct = dir(droid) for i in direct: if i == "m": print(i) print(i) #but the out is: wifiCheck #which is the last item in the list The thing is is that it's looking for "m" only as a complete string, which doesnt exist in the list. I dont know how to tell it to search for a str that STARTS with m.... Can anyone help? Thanks :)

28th Jun 2019, 5:36 PM
Dylan Campbell
Dylan Campbell - avatar
3 Answers
+ 3
you can use startswith() function you can write them with list comperhension like this. filewithm = [i for i in direct if i.startswith("m")] or if you want to simply print the items [print(i) for i in direct if i.startswith("m")] the first part before 'for' is an expression, its an action taken by the item in the list. and the if statement at the end act as a filter
28th Jun 2019, 7:11 PM
Taste
Taste - avatar
+ 1
Taste Thank you very much for this explanation... appreciate it. Although the i part before the "for" still confuses me. When you refer to the item in the list are you are referring to the second "i" or the "m"?
28th Jun 2019, 7:40 PM
Dylan Campbell
Dylan Campbell - avatar
+ 1
the i before for means, "do nothing to it, just store it directly to a new list" what i meant by the item is the second i, the one that is part of the for that pass the filter check if the filter exist
28th Jun 2019, 7:43 PM
Taste
Taste - avatar