Python 標題大小寫
Fariba Laiq
2023年1月30日
![Python 標題大小寫](/img/Python/feature-image---python-title-case.webp)
標題大小寫是一種句子風格,每個主要單詞的第一個字母都用大寫字母書寫,而對於次要單詞(如冠詞或介詞),第一個字母小寫。例如: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
作者: Fariba Laiq
I am Fariba Laiq from Pakistan. An android app developer, technical content writer, and coding instructor. Writing has always been one of my passions. I love to learn, implement and convey my knowledge to others.
LinkedIn