Development Tip

파이썬에서 문자가 대문자인지 확인하는 방법은 무엇입니까?

yourdevel 2020. 11. 10. 22:19
반응형

파이썬에서 문자가 대문자인지 확인하는 방법은 무엇입니까?


나는 이와 같은 문자열이

>>> x="Alpha_beta_Gamma"
>>> words = [y for y in x.split('_')]
>>> words
['Alpha', 'beta', 'Gamma']

목록 단어의 두 번째 요소가 소문자로 시작하고 문자열이 문자열 x = "Alpha_Beta_Gamma"을 인쇄해야하므로 X가 일치하지 않는다는 출력을 원합니다.


어쩌면 당신은 str.istitle

>>> help(str.istitle)
Help on method_descriptor:

istitle(...)
    S.istitle() -> bool

    Return True if S is a titlecased string and there is at least one
    character in S, i.e. uppercase characters may only follow uncased
    characters and lowercase characters only cased ones. Return False
    otherwise.

>>> "Alpha_beta_Gamma".istitle()
False
>>> "Alpha_Beta_Gamma".istitle()
True
>>> "Alpha_Beta_GAmma".istitle()
False

모든 단어가 대문자로 시작하는지 테스트하려면 다음을 사용하십시오.

print all(word[0].isupper() for word in words)

x="Alpha_beta_Gamma"
is_uppercase_letter = True in map(lambda l: l.isupper(), x)
print is_uppercase_letter
>>>>True

그래서 1 개의 문자열로 쓸 수 있습니다


words = x.split("_")
for word in words:
    if word[0] == word[0].upper() and word[1:] == word[1:].lower():
        print word, "is conformant"
    else:
        print word, "is non conformant"

이 코드를 사용할 수 있습니다.

def is_valid(string):
    words = string.split('_')
    for word in words:
        if not word.istitle():
            return False, word
    return True, words
x="Alpha_beta_Gamma"
assert is_valid(x)==(False,'beta')
x="Alpha_Beta_Gamma"
assert is_valid(x)==(True,['Alpha', 'Beta', 'Gamma'])

이렇게하면 유효한지, 어떤 단어가 잘못되었는지 알 수 있습니다.


이 정규식을 사용할 수 있습니다.

^[A-Z][a-z]*(?:_[A-Z][a-z]*)*$

샘플 코드 :

import re

strings = ["Alpha_beta_Gamma", "Alpha_Beta_Gamma"]
pattern = r'^[A-Z][a-z]*(?:_[A-Z][a-z]*)*$'

for s in strings:
    if re.match(pattern, s):
        print s + " conforms"
    else:
        print s + " doesn't conform"

코드 패드에서 볼 수 있듯이


list (str)를 사용하여 문자로 분리 한 다음 문자열을 가져오고 string.ascii_uppercase를 사용하여 비교할 수 있습니다.

문자열 모듈 확인 : http://docs.python.org/library/string.html

참고 URL : https://stackoverflow.com/questions/3668964/how-to-check-if-a-character-is-upper-case-in-python

반응형