Python 에서 문자열을 케밥 케이스로 변환하기

Beginner

This tutorial is from open-source community. Access the source code

소개

Python 에서 케밥 케이스 (kebab case) 문자열은 각 단어가 하이픈으로 구분된 문자열입니다. 예를 들어, "hello-world"는 케밥 케이스 문자열입니다. 이 챌린지에서는 주어진 문자열을 케밥 케이스로 변환하는 함수를 작성하는 과제를 수행하게 됩니다.

케밥 케이스 (kebabcase) 문자열

입력으로 문자열 s를 받아 케밥 케이스 버전의 문자열을 반환하는 Python 함수 to_kebab_case(s)를 작성하십시오. 이 함수는 다음 단계를 수행해야 합니다.

  1. 정규 표현식 (regexp) r"(_|-)+"를 사용하여 - 또는 _를 공백으로 바꿉니다.
  2. 문자열의 모든 단어를 일치시키고, str.lower()를 사용하여 소문자로 변환합니다.
  3. -를 구분 기호로 사용하여 모든 단어를 결합합니다.
from re import sub

def kebab(s):
  return '-'.join(
    sub(r"(\s|_|-)+"," ",
    sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+",
    lambda mo: ' ' + mo.group(0).lower(), s)).split())
kebab('camelCase') ## 'camel-case'
kebab('some text') ## 'some-text'
kebab('some-mixed_string With spaces_underscores-and-hyphens')
## 'some-mixed-string-with-spaces-underscores-and-hyphens'
kebab('AllThe-small Things') ## 'all-the-small-things'

요약

이 챌린지에서는 Python 에서 문자열을 케밥 케이스로 변환하는 방법을 배웠습니다. re.sub()를 사용하여 - 또는 _를 공백으로 바꾸고, re.sub()를 사용하여 문자열의 모든 단어를 일치시키고, str.lower()를 사용하여 소문자로 변환하고, str.join()을 사용하여 -를 구분 기호로 모든 단어를 결합했습니다.