Python中字符串處理函數 title() 函數的作用是把字符串中每個單詞的首字母變成大寫形式,其余字母變成小寫形式。
str.title()
str:是待處理的字符串或字符串變量;
參數:該函數沒有參數;
返回值:該函數返回處理后的字符串,該函數不會影響原字符串的內容和形式。
1、使用示例1
str1 = "python is simple"
print(str1.title()) # Python Is Simple
str1 = "Python is SIMPLE"
print(str1.title()) # Python Is Simple
str1 = "PYTHON IS SIMPLE"
print(str1.title()) # Python Is Simple
str1 = "PYthon iS SimPle"
print(str1.title()) # Python Is Simple
輸出結果:
Python Is Simple
Python Is Simple
Python Is Simple
Python Is Simple
從上面各例可以看出,不管原來字符串中字母的大小寫是怎么樣的,最后都被轉換成每個單詞的首字母是大寫形式,而其它字母是小寫的形式。
2、title()使用示例2
str1 = "I'm a student."
print(str1.title())
str1 = "Python3 is simple."
print(str1.title())
str1 = "123abc hi/t abc123"
print(str1.title())
str1 = "#abc$def&REt/r/nLOVE/tStorY"
print(str1.title())
輸出結果:
I'M A Student.
從以上例子的輸出結果可以看出,Python title()函數把句子中的撇號('),特殊字符(如#,¥,&,| 等),空白轉義字符(如/t,/r/n,/n等),數字,非字母字符等都視為一個單詞的分界符,然后把單詞的首字母變成大寫,其余字母變成小寫。
Python3 Is Simple.
123Abc Hi Abc123
#Abc$Def&Ret
Love Story
本文(完)
新聞熱點
疑難解答