파이썬에서 문자열을 제목 대소 문자로 변환하는 방법은 무엇입니까?
예:
HILO -> Hilo
new york -> New York
SAN FRANCISCO -> San Francisco
이 작업을 수행하는 라이브러리 또는 표준 방법이 있습니까?
title
문서에서 Right를 사용하지 않는 이유 :
>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
PascalCase를 정말로 원했다면 이것을 사용할 수 있습니다.
>>> ''.join(x for x in 'make IT pascal CaSe'.title() if not x.isspace())
'MakeItPascalCase'
이것은 항상 소문자로 시작하고 영숫자가 아닌 문자도 제거합니다.
def camelCase(st):
output = ''.join(x for x in st.title() if x.isalnum())
return output[0].lower() + output[1:]
def capitalizeWords(s):
return re.sub(r'\w+', lambda m:m.group(0).capitalize(), s)
re.sub
(대부분의 사람들이 익숙한 용도 인 문자열이 아니라) "대체"기능을 사용할 수 있습니다. 이 repl 함수는 re.Match
패턴의 각 일치에 대한 개체 와 함께 호출되며 결과 (문자열이어야 함)는 해당 일치에 대한 대체로 사용됩니다.
같은 것의 더 긴 버전 :
WORD_RE = re.compile(r'\w+')
def capitalizeMatch(m):
return m.group(0).capitalize()
def capitalizeWords(s):
return WORD_RE.sub(capitalizeMatch, s)
이것은 패턴 (일반적으로 좋은 형식으로 간주 됨)을 미리 컴파일하고 람다 대신 명명 된 함수를 사용합니다.
왜 하나 쓰지 않습니까? 다음과 같은 것이 귀하의 요구 사항을 충족시킬 수 있습니다.
def FixCase(st):
return ' '.join(''.join([w[0].upper(), w[1:].lower()]) for w in st.split())
참고 : 다른 답변을 제공하는 이유는 무엇입니까? 이 답변은 질문의 제목과 camelcase가 다음과 같이 정의된다는 개념을 기반으로합니다. 각 원래 단어가 대문자로 시작되도록 (나머지는 소문자) 연결된 일련의 단어 (공백 없음!) 시리즈의 첫 번째 단어 (완전히 소문자)를 제외하고. 또한 "모든 문자열"이 ASCII 문자 집합을 참조한다고 가정합니다. 유니 코드는이 솔루션에서 작동하지 않습니다).
단순한
위의 정의가 주어지면이 함수는
import re
word_regex_pattern = re.compile("[^A-Za-z]+")
def camel(chars):
words = word_regex_pattern.split(chars)
return "".join(w.lower() if i is 0 else w.title() for i, w in enumerate(words))
, 호출되면 이러한 방식으로
camel("San Francisco") # sanFrancisco
camel("SAN-FRANCISCO") # sanFrancisco
camel("san_francisco") # sanFrancisco
덜 간단
이미 낙타 케이스 문자열이 제공되면 실패합니다!
camel("sanFrancisco") # sanfrancisco <-- noted limitation
덜 간단
많은 유니 코드 문자열에서 실패합니다.
camel("México City") # mXicoCity <-- can't handle unicode
I don't have a solution for these cases(or other ones that could be introduced with some creativity). So, as in all things that have to do with strings, cover your own edge cases and good luck with unicode!
Potential library: https://pypi.org/project/stringcase/
Example:
import stringcase
stringcase.camelcase('foo_bar_baz') # => "fooBarBaz"
Though it's questionable whether it will leave spaces in. (Examples show it removing space, but there is a bug tracker issue noting that it leaves them in.)
I would like to add my little contribution to this post:
def to_camelcase(str):
return ' '.join([t.title() for t in str.split()])
just use .title(), and it will convert first letter of every word in capital, rest in small:
>>> a='mohs shahid ss'
>>> a.title()
'Mohs Shahid Ss'
>>> a='TRUE'
>>> b=a.title()
>>> b
'True'
>>> eval(b)
True
참고URL : https://stackoverflow.com/questions/8347048/how-to-convert-string-to-title-case-in-python
'Program Tip' 카테고리의 다른 글
char 배열을 비우는 방법? (0) | 2020.11.06 |
---|---|
Ruby on Rails에서 쿼리 문자열 인 것처럼 문자열 구문 분석 (0) | 2020.11.06 |
Python으로 Google 스프레드 시트에 액세스 (읽기, 쓰기)하려면 어떻게하나요? (0) | 2020.11.06 |
li의 두 번째 줄은 CSS 재설정 후 글 머리 기호 아래에서 시작합니다. (0) | 2020.11.06 |
--resource-rules는 mac os x> = 10.10에서 더 이상 사용되지 않습니다. (0) | 2020.11.06 |