데이터 - 기본 코드 및 알고리즘 연습/Codewar
[Codewars] Kebabize
Huin999
2021. 6. 23. 11:40
Codewars: Achieve mastery through challenge
Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.
www.codewars.com
▶ 문제 :
▶ 내 답안 :
import re
def kebabize(string):
string = re.sub('[0-9]','',string)
a = set([0]+[i for i in range(len(string)) if string[i] != string.lower()[i]]+[len(string)])
b = sorted(list(a))
c = []
for i in range(len(b)) :
try :
c.append(string[b[i]:b[i+1]].lower())
except :
pass
return '-'.join(c)
import re
def kebabize(string):
string = re.sub('[0-9]','',string)
if string == '' :
return ''
p = re.compile("[A-Z]")
result = p.sub(lambda m : '-'+ m.group(0).lower(), string)
if result[0] == '-' :
return result[1:]
else :
return result
▶ 모범답안 :
def kebabize(s):
return ''.join(c if c.islower() else '-' + c.lower() for c in s if c.isalpha()).strip('-')
import re
def kebabize(s):
return re.sub('\B([A-Z])', r'-\1', re.sub('\d', '', s)).lower()
▶ 배워야할 부분 : 정규표현식(r'\1'), islower(), isalpha()
import re
string = 'HiMyNameIsDebriswisdom'
1. r'\1' : itself(자기자신)
re.sub('([A-Z])',r'\1',string)
>>> 'HiMyNameIsDebriswisdom'
2. \B (빈칸아님), \b (빈칸)
re.sub('\B([A-Z])',r'-\1',string)
>>> 'Hi-My-Name-Is-Debriswisdom'
string = 'Hi My Name Is Debriswisdom'
re.sub(r'\b([A-Z])',r'-\1',string) # r에 주목 : \b는 r'\b'로 작성해야함
>>> '-Hi -My -Name -Is -Debriswisdom'
3. strip() 사용
re.sub('([A-Z])',r' \1',string).strip()
>>>'Hi My Name Is Debriswisdom'
re.sub('([A-Z])',r'-\1',string).strip('-')
>>>'Hi-My-Name-Is-Debriswisdom'
- 정규표현식 관련
위키독스
온라인 책을 제작 공유하는 플랫폼 서비스
wikidocs.net
- Case : Camel , Kebab, Snake, Pascal
[팁] 카멜 케이스 / 케밥 케이스 / 파스칼 케이스 / 스네이크 케이스 란?
camelCase kebab-case PascalCase snake_case 다양한 프로그래밍 관습들이 있지만, 그 중 케이스 스타일(case styles)에 대해 소개하고자 한다. 프로그래밍을 할 때, 변수나 클래스명을 지을 때 보통 공백(" ")을..
togll.tistory.com