파이썬 대문자, 소문자, 특수문자 갯수 구하기

조회수 5858회

p0Y123!@#THon 스트링 데이터에서 소문자, 대문자, 숫자, 특수문자 갯수 세는 방법을 모르겠어요

  • (•́ ✖ •̀)
    알 수 없는 사용자

2 답변

  • >>> 대문자 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    >>> 소문자 = "abcdefghijklmnopqrstuvwxyz"
    >>> 숫자 = "0123456789"
    >>> s = "p0Y123!@#THon"
    >>> s_u, s_l, s_n, s_s = "", "", "", ""
    >>> for c in s:
        if c in 대문자:
            s_u += c
        elif c in 소문자:
            s_l += c
        elif c in 숫자:
            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)
    
    • very Intuitive. good. dbwodlf3 2020.10.8 13:55
  • string 모듈에 소문자, 대문자, 숫자등이 정의되어 있습니다.

    >>> 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']
    
    

    파이썬의 기본모듈을 사용하면 반복구조를 만들필요가 없습니다.

    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})
    
    • very simple. good. dbwodlf3 2020.10.8 13:55

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)