简体   繁体   中英

in python: How to print message with the number of expected names started with lowercase

here I have to print friends names that start with upper letter only and except names with lowercase and then print message with the number of expected names started with lowercase

I need to know if my code is right or there is another easy way to print expected lower name ??

friends = ["Mohamed", "Shady", "ahmed", "eman", "Sherif"]

num =0

arr = []
while num < len(friends):
    if friends[num] != friends[num].lower():
        print(friends[num])
    num += 1    
else:
    
    mis = 0
    while mis < len(friends):
        if friends[mis].islower():
            arr.append(friends[mis])
        mis += 1
    print(f"all names have printed and the num of lower name is {len(friends) - len(arr)-1}")

You can filter the relevant friends with filter :

list(filter(lambda name: name[0].islower(), friends))

then you can use len to see how many

If you only want to check whether the name begins with a lower/upper case, then you can use a list comprehensions like below to do this:

friends = ["Mohamed", "Shady", "ahmed", "eman", "Sherif"]

upper_case = [print(name) for name in friends if name.strip()[0].isupper()]
print(f'Total lower case names: {len(friends) - len(upper_case)}')

This would also work if the names had a trailing whitespace. Also, using a for loop in your sample would be more apt instead of maintaining a separate counter with a while loop. The loop which you have is basically a for loop, but with extra steps.

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