파이썬 대문자, 소문자, 특수문자 갯수 구하기
조회수 5858회
-
(•́ ✖ •̀)
알 수 없는 사용자
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)
-
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})
댓글 입력