Coding/Python

[python]아스키코드

후__아 2024. 1. 29. 11:23

※ 내장함수 기억하기!

ord(문자) = 아스키코드
chr(아스키코드) = 문자

print(ord("A"))		# 65
print(ord("a"))		# 97
print(ord("z"))		# 122
print(ord("0"))		# 48
print(ord("9"))		# 57

print(chr(65))		# A
print(chr(48))		# 0
# 프로그래머스 lv0 문자 개수 세기
# "Programmers" A~z까지 count
def solution(s):
    li = [0]*52
    for i in s:
        if ord(i) < 97: # 대문자
            li[ord(i) - 65] += 1
        else: # 소문자
            li[ord(i) - 65 - 6] += 1
    return li

 

※ string.ascii_uppercase

대소문자 리스트 생성

['A', 'B', ..., 'Z']    # ascii_uppercase

['a', 'b', ..., 'z']    # ascii_lowercase

#프로그래머스 lv1 시저암호
import string
def solution(s, n):
    answer = ''
    L = [i for i in string.ascii_uppercase] * 2
    l = [i for i in string.ascii_lowercase] * 2
    for x in s:
        if x == ' ':
            answer += x
            continue
        if x in L:
            answer += L[ord(x) + n - ord("Z") - 1]
        else:
            answer += l[ord(x) + n - ord("z") - 1]
    return answer
    
# 다른 사람 풀이
def caesar(s, n):
    s = list(s)
    for i in range(len(s)):
        if s[i].isupper():
            s[i]=chr((ord(s[i])-ord('A')+ n)%26+ord('A'))
        elif s[i].islower():
            s[i]=chr((ord(s[i])-ord('a')+ n)%26+ord('a'))

    return "".join(s)

 

 

※ isupper(), islower() 기억!!!  https://hoooa.tistory.com/9

'Coding > Python' 카테고리의 다른 글

[python]시간/분/초 변환  (0) 2024.03.18
[python]bool 자료형/함수, 논리연산자  (0) 2024.03.14
[python]sum  (0) 2024.03.14
[python]문자열 format, raw string  (0) 2024.03.14
[python]map 함수  (0) 2024.03.14