본문 바로가기
파이썬

파이썬 Titlecasing a string with exceptions

by º기록 2020. 11. 3.
반응형

파이썬에서 문자열의 제목을 지정하는 표준 방법이 있습니까 (즉, 단어는 대문자로 시작하고 나머지 모든 대소 문자는 소문자가 있음) and , in 및 < code> of 소문자?

 

해결 방법

 

이것에는 몇 가지 문제가 있습니다. 분할 및 결합을 사용하는 경우 일부 공백 문자가 무시됩니다. 기본 제공 대문자 및 제목 메서드는 공백을 무시하지 않습니다.

>>> 'There     is a way'.title()
'There     Is A Way'

문장이 기사로 시작하는 경우 제목의 첫 단어가 소문자로 표시되는 것을 원하지 않습니다.

다음 사항을 염두에 두십시오.

import re 
def title_except(s, exceptions):
    word_list = re.split(' ', s)       # re.split behaves as expected
    final = [word_list[0].capitalize()]
    for word in word_list[1:]:
        final.append(word if word in exceptions else word.capitalize())
    return " ".join(final)

articles = ['a', 'an', 'of', 'the', 'is']
print title_except('there is a    way', articles)
# There is a    Way
print title_except('a whim   of an elephant', articles)
# A Whim   of an Elephant

 

참조 페이지 https://stackoverflow.com/questions/3728655

 

 

반응형

댓글