How to check if a character is upper-case in Python?

前端 未结 7 675
挽巷
挽巷 2020-12-08 09:18

I have a string like this

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


        
相关标签:
7条回答
  • 2020-12-08 09:28
    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"
    
    0 讨论(0)
  • 2020-12-08 09:33

    Use list(str) to break into chars then import string and use string.ascii_uppercase to compare against.

    Check the string module: http://docs.python.org/library/string.html

    0 讨论(0)
  • 2020-12-08 09:34

    Maybe you want 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
    
    0 讨论(0)
  • 2020-12-08 09:34

    You can use this code:

    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'])
    

    This way you know if is valid and what word is wrong

    0 讨论(0)
  • 2020-12-08 09:35

    You can use this regex:

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

    Sample code:

    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"
    

    As seen on codepad

    0 讨论(0)
  • 2020-12-08 09:45
    x="Alpha_beta_Gamma"
    is_uppercase_letter = True in map(lambda l: l.isupper(), x)
    print is_uppercase_letter
    >>>>True
    

    So you can write it in 1 string

    0 讨论(0)
提交回复
热议问题