python3のstr型の文字列の全ての文字が大文字かどうか、小文字かどうかなどを判定させる方法を紹介する。
基本的な判定メソッド
isupper() - 全て大文字かどうか判定
text1 = "HELLO"
text2 = "Hello"
text3 = "hello"
print(text1.isupper()) # True
print(text2.isupper()) # False
print(text3.isupper()) # False
islower() - 全て小文字かどうか判定
text1 = "HELLO"
text2 = "Hello"
text3 = "hello"
print(text1.islower()) # False
print(text2.islower()) # False
print(text3.islower()) # True
istitle() - タイトルケースかどうか判定
text1 = "Hello World"
text2 = "HELLO WORLD"
text3 = "hello world"
print(text1.istitle()) # True
print(text2.istitle()) # False
print(text3.istitle()) # False
使用例
text = "Python Programming"
print(f"元の文字列: {text}")
print(f"isupper(): {text.isupper()}")
print(f"islower(): {text.islower()}")
print(f"istitle(): {text.istitle()}")
# 数字や記号が含まれる場合
text2 = "Hello123!"
print(f"\n文字列: {text2}")
print(f"isupper(): {text2.isupper()}")
print(f"islower(): {text2.islower()}")
print(f"istitle(): {text2.istitle()}")
出力結果:
元の文字列: Python Programming
isupper(): False
islower(): False
istitle(): True
文字列: Hello123!
isupper(): False
islower(): False
istitle(): True
注意点
- 数字や記号は大文字・小文字の判定に影響しない
- 空白文字がある場合、各単語の最初の文字が大文字で他が小文字の時に
istitle()
がTrue
になる - 文字列に英字が含まれていない場合、
isupper()
とislower()
は両方ともFalse
を返す