10个有用的Python字符串函数小结

10个有用的Python字符串函数小结,博智网带你了解详细信息 。
目录

  • 前言
  • 一、capitalize() 函数
  • 二、lower( ) 函数
  • 三、title( ) 函数
  • 四、casefold() 函数
  • 五、upper( ) 函数
  • 六、count( ) 函数
  • 七、find( ) 函数
  • 八、replace() 函数
  • 九、swapcase( ) 函数
  • 十、join () 函数

前言Python 字符串是一个内置的类型序列 。字符串可用于处理 Python 中的文本数据 。Python 字符串是 Unicode 点的不可变序列 。在 Python 中创建字符串是最简单易用的 。要在 Python 中创建字符串,我们只需将文本括在单引号和双引号中 。Python 对单引号和双引号语句的处理方式相同 。因此,在本文中,我们将讨论 Python 中用于数据分析和数据操作的一些重要且有用的字符串函数,主要用于自然语言处理(NLP) 。
我们将在本文中讨论的 Python 字符串函数如下:

一、capitalize() 函数
capitalize() 函数返回一个字符串,其中第一个字符是大写 。
语法:string.capitalize()
示例 1:使给定句子中的第一个字母大写
string = "CSDN is the largest developer community in China" print(string.capitalize())
输出:
Csdn is the largest developer community in china
示例 2:如果第一个字符是数字而不是字符会发生什么
string = '3th CSDN force plan activities are very good' print(string.capitalize())
输出:
3th csdn force plan activities are very good

二、lower( ) 函数
lower() 函数返回一个字符串,其中给定字符串中的所有字符都是小写 。这个函数对符号和数字没有任何作用,即,只是忽略了这些东西 。
语法:string.lower()
示例 1:小写给定字符串
string = "Haiyong is an excellent CSDN blogger" print(string.lower())
输出:
haiyong is an excellent csdn blogger
示例 2: 如果有数字而不是字符会发生什么
string = '3th CSDN force plan activities are very good' print(string.lower())
输出:
3th csdn force plan activities are very good

三、title( ) 函数title() 函数返回一个字符串,其中字符串中每个单词的第一个字符都是大写 。它就像标题或标题 。
如果字符串中的任何单词包含数字或符号,则此函数将其后的第一个字母转换为大写 。
语法:string.title()
【10个有用的Python字符串函数小结】示例 1:使每个单词的第一个字母大写
string = "The blog you are reading will be on the hot list" print(string.title())
输出:
The Blog You Are Reading Will Be On The Hot List
示例 2:如果有数字而不是字符会发生什么
string = '10 useful Python string functions you must know' print(string.title())
输出:
10 Useful Python String Functions You Must Know

四、casefold() 函数
casefold() 函数返回一个字符串,其中所有字符都是小写 。
这个函数类似于lower()函数,但是casefold()函数更强大,更激进,这意味着它将更多的字符转换成小写,并且在比较两个字符串时会找到更多的匹配项,并且都使用casefold()进行转换 功能 。
语法:string.casefold()
示例 1:将给定的字符串变为小写
string = "CSDN is the largest developer community in China" print(string.casefold())
输出:
csdn is the largest developer community in china
示例 2:如果有数字而不是字符会发生什么
string = '10 useful Python string functions you must know' print(string.casefold())
输出:
10 useful python string functions you must know

五、upper( ) 函数
upper() 函数返回一个字符串,其中给定字符串中的所有字符都为大写 。这个函数对符号和数字没有任何作用,即,只是忽略了这些东西 。
语法:string.upper()
示例 1:给定字符串的大写
string = "CSDN is the largest developer community in China" print(string.upper())
输出:
CSDN IS THE LARGEST DEVELOPER COMMUNITY IN CHINA
示例 2:如果有数字而不是字符会发生什么
string = '10 useful Python string functions you must know' print(string.upper())
输出:
10 USEFUL PYTHON STRING FUNCTIONS YOU MUST KNOW

六、count( ) 函数

推荐阅读