Python str.capitalize()和str.title()的区别 |
您所在的位置:网站首页 › python中capitalize的用法和作用 › Python str.capitalize()和str.title()的区别 |
Python str.capitalize()和str.title()的区别
title() 和 capitalize() 方法都有类似的功能:就是将第一个字符大写。下面下面来看看它们两个的区别。 方法1:title() Python中的 title() 函数是Python字符串方法,用于将字符串中每个单词的第一个字符转换为大写,其余字符转换为小写,并返回一个新字符串。 语法: str.title() 参数: None 返回值: 这个函数返回一个字符串,每个单词的首字母都是大写的,其余的字母都是小写。 示例代码: # Python Title() Method Example str1 = 'geekdocs 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 = 'ANDY pass JaVa'.title() print('Second Output after Title() method is = ', str3) str4 = 'student anD teaCher'.title() print('Third Output after Title() method is = ', str4) str5 = '1122'.title() print('Fourth Output after Title() method is = ', str5)运行结果: First Output after Title() method is = geekdocs For Geeks Converted String is = geekdocs For Geeks Original String is = geekdocs foR geEks Second Output after Title() method is = Andy Pass Java Third Output after Title() method is = Student And Teacher Fourth Output after Title() method is = 1122方法2:capitalize() 在Python中, capitalize() 方法将字符串的第一个字符转换为大写字母(大写)。如果字符串的第一个字符是大写的,那么它就会返回原始字符串。 语法- str.capitalize()参数: NA 返回类型: 该函数返回一个首字母为大写,其余字母为小写的字符串。 例子: # Python program to demonstrate the # use of capitalize() function # capitalize() first letter of # string. name = "geekdocs for geeks"\n print(name.capitalize()) # demonstration of individual words # capitalization to generate camel case name1 = "geekdocs"\nname2 = "for"\nname3 = "geeks"\nprint(name1.capitalize() + name2.capitalize() + name3.capitalize())输出结果: geekdocs for geeks geekdocsForGeeks title()和capitalize()的区别它们之间的区别是:Python字符串方法 title() 返回一个字符串的副本,其中所有单词的第一个字符都被大写,而字符串方法 capitalize() 返回一个字符串的副本,其中只有整个字符串的第一个单词被大写。 例子 str = "geekdocs for geeks"\nstr.title() # will return geekdocs For Geeks str.capitalize() #will return geekdocs for geeks示例代码: str1 = "my name is abc"\nstr2 = "geekdocs for geeks"\n # using title() print(str1.title()) print(str2.title()) # using capitalize() print(str1.capitalize()) print(str2.capitalize())输出结果: My Name Is Abc geekdocs For Geeks My name is abc geekdocs for geeks |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |