📜  str.capitalize() VS str.title() 的区别

📅  最后修改于: 2021-09-13 02:55:13             🧑  作者: Mango

title()capitalize()都具有类似的首字符大写功能。让我们看看两者之间的区别。

标题()

在Python标题()函数是Python字串方法其用于在每个字为大写的第一个字符和剩余的字符转换为小写字符串,并返回一个新的字符串。

例子:

Python3
# Python Title() Method Example 
     
str1 = 'geeKs foR geEks'
str2 = str1.title() 
print ('First Output after Title() method is = ', str2) 
    
# observe the original string 
print ('Converted String is = ', str1.title()) 
print ('Original String is = ', str1 )
     
# Performing title() function directly 
str3 = 'ASIPU pawan kuMAr'.title() 
print ('Second Output after Title() method is = ', str3) 
     
str4 = 'stutya kUMari sHAW'.title() 
print ('Third Output after Title() method is = ', str4) 
     
str5 = '6041'.title() 
print ('Fourth Output after Title() method is = ', str5)


Python3
# Python program to demonstrate the  
# use of capitalize() function  
    
# capitalize() first letter of  
# string. 
name = "geeks for geeks"
    
print(name.capitalize())  
    
# demonstration of individual words  
# capitalization to generate camel case 
name1 = "geeks"
name2 = "for"
name3 = "geeks"
print(name1.capitalize() + name2.capitalize() 
                         + name3.capitalize())


Python3
str1 = "my name is xyz"
str2 = "geeks for geeks"
  
# using title()
print(str1.title())
print(str2.title())
  
# usng capitalize()
print(str1.capitalize())
print(str2.capitalize())


输出:

First Output after Title() method is =  Geeks For Geeks
Converted String is =  Geeks For Geeks
Original String is =  geeKs foR geEks
Second Output after Title() method is =  Asipu Pawan Kumar
Third Output after Title() method is =  Stutya Kumari Shaw
Fourth Output after Title() method is =  6041

大写()

在Python, capitalize()方法将字符串的第一个字符转换大写(大写)字母。如果字符串的第一个字符为大写,则返回原始字符串。

例子:

蟒蛇3

# Python program to demonstrate the  
# use of capitalize() function  
    
# capitalize() first letter of  
# string. 
name = "geeks for geeks"
    
print(name.capitalize())  
    
# demonstration of individual words  
# capitalization to generate camel case 
name1 = "geeks"
name2 = "for"
name3 = "geeks"
print(name1.capitalize() + name2.capitalize() 
                         + name3.capitalize())

输出:

Geeks for geeks
GeeksForGeeks

title() 和 capitalize() 的区别

它们之间的区别在于Python字符串方法 title() 返回字符串的副本,其中所有单词的第一个字符都大写,而字符串方法 capitalize() 返回字符串的副本,其中只有单词的第一个单词整个字符串大写。

例子:

str = "geeks for geeks"
str.title() will return Geeks For Geeks
str.capitalize() will return Geeks for geeks

蟒蛇3

str1 = "my name is xyz"
str2 = "geeks for geeks"
  
# using title()
print(str1.title())
print(str2.title())
  
# usng capitalize()
print(str1.capitalize())
print(str2.capitalize())

输出:

My Name Is Xyz
Geeks For Geeks
My name is xyz
Geeks for geeks