How to check if a string is title case in Python

2 Answers

0 votes
def is_title_case(s: str) -> bool:
    return s.istitle();


def main():
    tests = [
        "Hello World",
        "Hello world",
        "hello World",
        "Python Programming Language",
        "This Is Fine",
        "This is Not Fine"
    ]

    for t in tests:
        print(f'"{t}" -> {is_title_case(t)}')


if __name__ == "__main__":
    main()


'''
run:

"Hello World" -> True
"Hello world" -> False
"hello World" -> False
"Python Programming Language" -> True
"This Is Fine" -> True
"This is Not Fine" -> False

'''

 



answered Nov 9, 2018 by avibootz
edited 4 hours ago by avibootz
0 votes
def is_title_case(s):
    return all(word[:1].isupper() and word[1:].islower()
               for word in s.split() if word)
 
def main():
    tests = [
        "Hello World",
        "Hello world",
        "hello World",
        "Python Programming Language",
        "This Is Fine",
        "This is Not Fine"
    ]
 
    for t in tests:
        print(f'"{t}" -> {is_title_case(t)}')
 
 
if __name__ == "__main__":
    main()
 
 
 
'''
run:
 
"Hello World" -> True
"Hello world" -> False
"hello World" -> False
"Python Programming Language" -> True
"This Is Fine" -> True
"This is Not Fine" -> False
 
'''

 



answered 4 hours ago by avibootz
...