Python中字符串處理函數(shù) title() 函數(shù)的作用是把字符串中每個(gè)單詞的首字母變成大寫形式,其余字母變成小寫形式。
str.title()
str:是待處理的字符串或字符串變量;
參數(shù):該函數(shù)沒有參數(shù);
返回值:該函數(shù)返回處理后的字符串,該函數(shù)不會(huì)影響原字符串的內(nèi)容和形式。
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
輸出結(jié)果:
Python Is Simple
Python Is Simple
Python Is Simple
Python Is Simple
從上面各例可以看出,不管原來字符串中字母的大小寫是怎么樣的,最后都被轉(zhuǎn)換成每個(gè)單詞的首字母是大寫形式,而其它字母是小寫的形式。
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())
輸出結(jié)果:
I'M A Student.
從以上例子的輸出結(jié)果可以看出,Python title()函數(shù)把句子中的撇號(hào)('),特殊字符(如#,¥,&,| 等),空白轉(zhuǎn)義字符(如/t,/r/n,/n等),數(shù)字,非字母字符等都視為一個(gè)單詞的分界符,然后把單詞的首字母變成大寫,其余字母變成小寫。
Python3 Is Simple.
123Abc Hi Abc123
#Abc$Def&Ret
Love Story
本文(完)
新聞熱點(diǎn)
疑難解答
圖片精選