python3のstr型の文字列の大文字小文字を入れ替えたり、大文字を小文字に変換したりする方法を紹介する。
基本的な変換メソッド
upper() - 全て大文字に変換
text = "Hello World"
print(text.upper()) # HELLO WORLD
lower() - 全て小文字に変換
text = "Hello World"
print(text.lower()) # hello world
swapcase() - 大文字と小文字を入れ替え
text = "Hello World"
print(text.swapcase()) # hELLO wORLD
capitalize() - 最初の文字を大文字に、残りを小文字に
text = "hello world"
print(text.capitalize()) # Hello world
title() - 各単語の最初の文字を大文字に
text = "hello world python"
print(text.title()) # Hello World Python
使用例
text = "Python Programming"
print(f"元の文字列: {text}")
print(f"upper(): {text.upper()}")
print(f"lower(): {text.lower()}")
print(f"swapcase(): {text.swapcase()}")
print(f"capitalize(): {text.capitalize()}")
print(f"title(): {text.title()}")
出力結果:
元の文字列: Python Programming
upper(): PYTHON PROGRAMMING
lower(): python programming
swapcase(): pYTHON pROGRAMMING
capitalize(): Python programming
title(): Python Programming
これらのメソッドを使い分けることで、文字列の大文字小文字を自由に変換できます。