Find the number of Python uppercase, lowercase, and special characters

Asked 2 years ago, Updated 2 years ago, 40 views

p0Y123!@#I don't know how to count lowercase, uppercase, number, and special characters in the THon string data.

python string

2022-09-20 19:53

2 Answers

>>> uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
>>> Lowercase = "abcdefghijklmnopqrstuvwxyz"
>>> Number = "0123456789"
>>> s = "p0Y123!@#THon"
>>> s_u, s_l, s_n, s_s = "", "", "", ""
>>> for c in s:
    If c in uppercase:
        s_u += c
    elifc in lower case:
        s_l += c
    elif c in number:
        s_n += c
    else:
        s_s += c


>>> s_u, s_l, s_n, s_s
('YTH', 'pon', '0123', '!@#')
>>> len(s_u), len(s_l), len(s_n), len(s_s)
(3, 3, 4, 3)


2022-09-20 19:53

Lowercase letters, uppercase letters, numbers, etc. are defined in the string module.

>>> s = 'p0Y123!@#THon'
>>> import string
>>> string.digits
'0123456789'
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> list(filter(lambda c:c in string.ascii_lowercase, s))
['p', 'o', 'n']

With Python's basic module, you don't need to create an iterative structure.

import itertools as it
import string
from collections import Counter

classification_char_type = lambda c: 'lower' if c in string.ascii_lowercase else 'upper' if c in string.ascii_uppercase else 'digit' if c in string.digits else 'special'

s = 'p0Y123!@#THon'
counter = Counter(list(iter(lambda s=iter(s): classification_char_type(next(s)), [])))
print(counter)

Counter({'digit': 4, 'lower': 3, 'upper': 3, 'special': 3})


2022-09-20 19:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.