Issue
How to print words starting from a particular letter in python without using functions, but using methods or loops.
1 ) I got a string and wants to print words starting with 'm'
St= "where is my mobile"
result = "my", "mobile"
2 ) For the below list, how to output list starting with "p", which can be either lower or upper.
List = ['mobile',"pencil","Pen","eraser","Book"]
RESULT= "pencil","pen".
Thanks
Nb: This is not a homework, only a python newbie
Solution
Use str.startswith
Ex:
St= "where is my mobile"
for i in St.split():
if i.startswith("m"):
print(i)
Output:
my
mobile
Using filter
Ex:
L = ['mobile',"pencil","Pen","eraser","Book"]
print( list(filter(lambda x: x.lower().startswith("p"), L)) )
Output:
['pencil', 'Pen']
Answered By - Rakesh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.