HOWTO · Python

Python タイトルケース

このチュートリアルでは、任意の文をタイトルケースに変換する方法を示します。

このページの内容

タイトルケースは、すべての主要な単語の最初の文字が大文字で書かれ、マイナーな単語(記事や前置詞など)の場合、最初の文字が小さい文で書かれる文スタイルです。例:I Am a Programmer from France はタイトルケースに書かれています。

Python で任意の文をタイトルケースに変換するには、文字列で title() 関数を使用するか、titlecase モジュールで使用できる titlecase() 関数を使用します。

Python で title() 関数を使用したタイトルケース

任意の文字列を使用して title() 関数を呼び出し、タイトルケースに変換できます。これは、文字列で使用できる組み込みメソッドです。

サンプルコード:

sentence = "i am a programmer from france and i am fond of python"
print("Sentence before:", sentence)
sentence = sentence.title()
print("Sentence now:", sentence)

出力:

Sentence before: i am a programmer from france and i am fond of python
Sentence now: I Am A Programmer From France And I Am Fond Of Python

Python で titlecase モジュールを使用したタイトルケース

文をタイトルケースに変換する別の方法は、titlecase モジュールをインポートし、その関数 titlecase() に文字列を渡すことです。注:このモジュールを使用するには、最初にこのモジュールをインストールする必要があります。

サンプルコード:

from titlecase import titlecase

sentence = "i am a programmer from france and i am fond of python"
print("Sentence before:", sentence)
sentence = titlecase(sentence)
print("Sentence now:", sentence)

出力:

Sentence before: i am a programmer from france and i am fond of python
Sentence now: I Am A Programmer From France And I Am Fond Of Python