我想计算一个字符串中的偶数和大写字母的数量?

时间:2018-01-14 12:26:46

标签: python

import re
msg = input("Please type: ")
print("Capital Letters: ", sum(1 for c in msg if c.isupper()))
a = re.findall(',*\d*[02468]',msg)
print (a)

#OUTPUT:     请输入:dfg2468789fghHHH     大写字母:3     [ '246878']

2 个答案:

答案 0 :(得分:1)

message = input('Please type: ')


capitals = (sum(1 for c in message if c.isupper()))

even = ['0','2','4','6','8']
evennumbers = []
for x in range(0,len(message)):
    if message[x] in even:
        evennumbers.append(message[x])

evens = ''
for x in range(0,len(evennumbers)):
    evens = evens + str(evennumbers[x])

capitals = str(capitals)
evens = "['" + evens + "']"

print('Capitals : ' + capitals, evens)

答案 1 :(得分:0)

#to print the length of uppercase and print the even number present in the input

        msg = input("Please type: ")
        print("Capital Letters: ", len([x for x in msg if x.isupper()]))
        print("even numbers:", len([y for y in filter(lambda x: 
        x.isdigit(), msg) if int(y)%2 ==0]))

#long code to print the same:
            message = input("enter alphanumeric:")
            capitals = (sum(1 for c in message if c.isupper()))
            evens = ['0','2','4','6','8']
            evennumbers = []
            for x in range(0,len(message)):
                if(message[x] in evens):
                    evennumbers.append(message[x]) 
            capitals = str(capitals)
            evennumbers = str(evennumbers)
            print('Capitals : ' + capitals + ', Evens : ' + evennumbers')


#short code to print the length of Uppercase and even numbers in the input

        msg = input("Please type: ")
        print("Capital Letters: ", len([x for x in msg if x.isupper()]))
        print("even numbers:", len([y for y in filter(lambda x: x.isdigit(), msg) if int(y)%2 ==0]))