반응형

파이썬, 한글은 2글자로 계산하는 문자열 길이

 

글. 수알치 오상문

 

아래 예제는 Windows 환경에서 테스트에 테스트했습니다. 


[소스 코드] 
import re

# 방법 1 :  참조  https://databook.tistory.com/66 
def korlen1(s):    
  korP = re.compile('[\u3131-\u3163\uAC00-\uD7A3]+',re.U)    
  temp = re.findall(korP, s)    
  temp_len = 0    
  for item in temp:
    temp_len = temp_len + len(item)
  return len(s) + temp_len

# 방법 2 : 한글 코드에 해당하는지 크기를 비교하는 방식
def korlen2(s):     
  temp_len = len(s)
  for c in s:
    if ('가' <= c <= '힣') or ('ㄱ' <= c <= 'ㅎ'):
      temp_len += 1
  return temp_len

      
s = "안녕하세요, Hello!, ㅎㅎ"   

print(len(s))         # 17
print(korlen1(s))  # 24
print(korlen2(s))  # 24

 

반응형

+ Recent posts