> 文档中心 > Python零基础入门篇 - 18 - Python字符串常用方法

Python零基础入门篇 - 18 - Python字符串常用方法


前言
✌ 作者简介:渴望力量的哈士奇,大家可以叫我 🐶哈士奇🐶 。(我真的养了一只哈士奇)
📑 个人主页:渴望力量的哈士奇主页
📫 如果文章知识点有错误的地方,请指正!和大家一起学习,一起进步👀
🔥 如果感觉博主的文章还不错的话,还请不吝👍关注、点赞、收藏三连支持👍一下博主哦
💬 人生格言:优于别人,并不高贵,真正的高贵应该是优于过去的自己。💬

📕系列专栏::
               👍 Python全栈系列 - [更新中]    ➡️➡️➡️ 【 本文在该系列】
               👋 网安之路系列
​                       🍋 网安之路踩坑篇
​                       🍋 网安知识扫盲篇
​                       🍋 Vulhub 漏洞复现篇
​                       🍋 Shell脚本编程篇
​                       🍋 Web攻防篇  ➡️➡️➡️ 2021年9月3日停止更新,转战先知等安全社区
​                       🍋 渗透工具使用集锦  ➡️➡️➡️ 2021年9月3日停止更新,转战先知等安全社区
​                ⭐️ 点点点工程师系列
​                       🍹 测试神器 - Charles 篇
​                       🍹 测试神器 - Fiddler 篇
​                       🍹 测试神器 - Jmeter 篇
​                       🍹 自动化 - RobotFrameWork 系列
​                       🍹 自动化 - 基于 JAVA 实现的WEB端UI自动化
                       🍹 自动化 - 基于 MonkeyRunner 实现的APP端UI自动化
​                🤗 2019年之前学习Python留下的乱七八糟系列

                                                                                  🎉🎉欢迎持续关注🎉🎉

Python零基础入门篇 - 18 - Python字符串常用方法

文章目录

    • 什么是对象?
    • Python 万物皆是对象
    • 字符串的索引
      • 索引[]
      • 索引[:]
    • 字符串的常用方法
      • find()函数 与 index()函数
      • startswith() 函数与 endswith() 函数
      • capitalize () 函数
        • capitalize()函数小练习
      • casefold()函数与lower()函数
        • casefold()函数与lower()函数 小练习
      • upper() 函数
      • swapcase() 函数
      • zfill() 函数
      • count() 函数
      • strip()函数
      • replace()函数
      • join() 函数
      • split() 函数
    • 字符串中返回 bool 类型的函数集合
      • isspace() 函数
      • istitle() 函数
      • isupper() 函数 与 islower() 函数

接下来我们会进入 字符串常用方法的应用阶段,重点学习字符串的内置函数。正式学习之前,我们要先了解一个词 对象 (划重点,不是男女朋友!),只有知道 对象是什么?才能更好的帮助我们接下来的学习。

什么是对象?

对于 Python 来说,对象的概念,更像是身份的概念,我们可以理解为 每一个 变量 其实就是 对象。

  • Python 中一切皆是对象
  • 每个对象都有自己的属性和方法
  • 对象的特点就是它的属性,它的功能就是它的方法,也可以说是函数。比如字符串就有很多内置函数来帮助我们处理字符串。

Python 万物皆是对象

Python里面有一句话:万物解释对象

在编程领域中,通常把现实世界中的实体称为对象,例如:

  • 香蕉、苹果、橘子

  • 男人、女人、小孩

  • 飞机、地铁、突突车

  • 平房、楼房、小别墅

对象指的是一个具体的实体,不用于指代一个抽象的群体(或者也可以说是一个实体所处的群体)

  • 香蕉是一个具体的水果,所以可以说香蕉是一个对象
  • 它是一种水果,但水果是一个抽象的概念,指的是一群可食用的含水分和糖分较多的植物果实
  • 你可以说,香蕉、苹果、橘子是水果,但是不能说水果就只能是香蕉、只能是苹果、只能是橘子…
  • 所以不能说水果是一个对象

类似的,飞机、地铁这些具体的交通工具可以被称为对象,但是不能说交通工具是一个对象

字符串的索引

学习字符串的常用方法之前,我们再来吻戏一下字符串的索引

索引[]

通过索引 [] 获取字符串中指定位置的字符,示例如下:

>>> s = 'Python'>>> s[0]'P'>>> s[1]'y'>>> s[2]'t'>>> s[3]'h'>>> s[4]'0'>>> s[5]'n'
  • 在 Python 中,单个字符也被当作字符串来处理,即该字符串只包含一个字符
  • 在第 2 行,获取字符串 s 的第 0 个字符 ‘P’
  • 在第 4 行,获取字符串 s 的第 1 个字符 ‘y’
  • 在第 6 行,获取字符串 s 的第 1 个字符 ‘t’
  • 在第 8 行,获取字符串 s 的第 1 个字符 ‘h’
  • 在第 10 行,获取字符串 s 的第 1 个字符 ‘o’
  • 在第 12 行,获取字符串 s 的第 1 个字符 ‘n’

索引[:]

在 Python 中,使用语法 string [start:end],获取字符串 string 中在 [start, end) 范围的子字符串。

注意范围 [start, end) 包含 start,不包含 end。也可以理解为是列表的 左闭右开原则

举例如下:

>>> s = 'Python'>>> s[1]'y'>>> s[2]'t'>>> s[3]'h'>>> s[0:5]'Pytho'
  • 在第 2 行,获取字符串 s 的第 1 个字符 ‘m’
  • 在第 4 行,获取字符串 s 的第 2 个字符 ‘o’
  • 在第 6 行,获取字符串 s 的第 3 个字符 ‘o’
  • 在第 8 行,获取字符串 s 中从 1 开始、到 4 结束的字符串 ‘mooc’,使用 s [1:4] 表示该范围,注意该范围包括字符串的第 1 个字符、不包括第 4 个字符。

字符串的常用方法

find()函数 与 index()函数

find() 函数与 index() 函数的功能:都是返回你想找的成员(元素)的位置

find() 函数的用法:str = string.finde(item) item:想要查询匹配的元素,返回一个整型

index() 函数的用法:str = string.index(item) item:想要查询匹配的元素,返回一个整型或者报错

附:字符串里的位置是从左向右从下标位[0]开始计算

find() 函数与 index() 函数的区别:

  • 如果 find() 函数 找不到c成员(元素),会返回 -1
  • 如果 index()函数 找不到成员(元素),会导致程序报错
info = "Python is good code"print(info.find("P"))print(info.find("good"))print(info.find("Java"))# >>> 0# >>> 10# >>> -1
info = "Python is good code"print(info.index("P"))print(info.index("good"))print(info.index("Java"))# 直接报错(语法错误) 'ValueError: substring not found'# >>> 0# >>> 10

startswith() 函数与 endswith() 函数

startswith() 函数的功能:判断字符串 开始位 是否是某成员(元素),可以指定统计的范围,[start,end) 左闭区间右开区间

startswith() 函数的用法:str = string.startswith(item) item:想要查询匹配的元素,返回一个布尔值

endswith() 函数的功能:判断字符串 结尾 是否是某成员(元素),可以指定统计的范围,[start,end) 左闭区间右开区间

startswith() 函数的用法:str = string.endswith(item) item:想要查询匹配的元素,返回一个布尔值

示例如下:

info = 'Python is good'print(info.startswith('Python'))print(info.startswith('Java'))print(info.endswith('good'))print(info.endswith('bad'))# >>> True# >>> False# >>> True# >>> Falsestring_test = "this is string example"print(string_test.startswith('this'))    # 字符串是否以 this 开头print(string_test.startswith('string', 8))      # 从第九个字符开始的字符串是否以 string 开头print(string_test.startswith('this', 2, 4))     # 从第2个字符开始到第四个字符结束的字符串是否以 this 开头# >>> True# >>> True# >>> False

capitalize () 函数

capitalize 的功能 : 将字符串的首字母大写

capitalize 的用法:str = string.capitalize() ;

示例如下:

>>> str = 'string'>>> str.capitalize()'String'

capitalize() 的注意事项:

  • 只对首字母有效
  • 只对字母有效
  • 已经是大写,则无效


capitalize()函数小练习

将han meimei转换成规范的英文名字,打印实现姓、名首字母都是大写

name_1="han"name_2="meimei"print(name_1.capitalize() + ' ' +name_2.capitalize())# >>> 输出结果 'Han Meimei'

casefold()函数与lower()函数

casefold()函数与lower()函数 的功能 : 将字符串的全体字符小写

casefold()函数与lower()函数 的用法:str = string.casefold() , str = string.lower() ;

示例如下:

>>> str_01 = 'Hello'>>> str_01.casefold()'hello'>>> str_02 = 'World'>>> str_02.lower()'world'

casefold()函数与lower()函数 的注意事项:

  • 只对字符串的字母有效
  • 已经是小写的字母无效
chinese = "你好,世界"english = "Hello,World"test_str = "test@1.com$OK"print(chinese.casefold())print(chinese.lower())print(english.casefold())print(english.lower())print(test_str.casefold())print(test_str.lower())

既然 casefold()函数与lower()函数 都可以将字符串的全体字符转为小写,那么又有什么区别呢?

其实还是有区别的,lower()函数是很早之前就存在的将字符串小写的方法,而casefold()函数则是 Python3.3版本之后才引入的小写方法。lower()函数是将英文字符进行小写,但是对德语等其他非英语字符就失去了效果,这个时候就是 casefold() 函数大显身手的时候了。

casefold()函数与lower()函数 小练习

将下列三个验证码全部转为 小写

str_1 = “NAh8”

str_2 = “Sn6H”

str_3 = “HKFM”

str_1 = "NAh8"str_2 = "Sn6H"str_3 = "HKFM"print (str_1.lower())print (str_2.casefold())print (str_3.lower())

upper() 函数

upper() 函数的功能:将字符串全体大写

upper() 函数的用法:str = string.upper()

示例如下:

>>> str = 'string'>>> str.upper()'STRING'

capitalize 的注意事项:

  • 只对字符串的字母有效
  • 已经是大写的字母无效
str_test = 'Hello World'print(str_test.upper())# >>> 'HELLO WORLD'

swapcase() 函数

swapcase() 函数的功能:将字符串中的字符进行大小写转换

swapcase() 函数的用法:str = string.swapcase()

swapcase() 函数的注意事项:只对字符串的字母有效

info_one = 'Python is good'info_two = 'pthon web is so esay'print(info_one.swapcase())print(info_two.swapcase())

zfill() 函数

zfill() 函数的功能:为字符串定义长度,如果现有字符串长度不满足,缺少的部分自动用 0 补齐

zfill() 函数的用法:str = string.zfill(width) width:新字符串希望的长度

zfill() 函数的注意事项:与字符串的字符没有关系;如果定义的字符串长度小于当前字符串长度,则不会发生变化。

info = "Hello World"print(info.zfill(10))print(info.zfill(15))print(info.zfill(20))

count() 函数

count() 函数的功能:统计字符串出现的次数;或者说返回当前字符串某个成员(元素)出现的次数

count() 函数的用法:str = string.zfill(item) item:查询个数/次数的元素

count() 函数的注意事项:如果查询的成员(元素)不存在,则返回 0

info = ''' Please send this message to those people who mean something to you,to those who have touched your life in  one way or another,to those who make you smile when you really need it,to those that make you see the  brighter side of things when you are really down,to those who you want to let them know that you appreciate  their friendship. And if you don’t, don’t worry,nothing bad will happen to you,you will just miss out on the  opportunity to brighten someone’s day with this message. '''this_count = info.count('this')you_count = info.count('you')love_count = info.count('love')print('"this"出现的次数为: ' + str(this_count) + '次')# >>> "this"出现的次数为: 2次print('"you"出现的次数为: ' + str(you_count) + '次')# >>> "you"出现的次数为: 11次print('"love"出现的次数为: ' + str(love_count) + '次')# >>> "maybe"出现的次数为: 0次

strip()函数

strip() 函数的功能 :去掉字符串两边的指定元素,默认是空格

strip() 函数的用法 :str = string.strip(item) ,括弧里传一个想要去掉的成员(元素),可以不填写

strip() 函数的拓展 :

  • 传入的元素如果不在开头或者结尾则无效
  • lstrip 仅去掉字符串开头的指定元素或者是空格
  • rstrip 仅去掉字符串结尾的指定元素或者是空格

示例如下:

info = '    Jack is a good boy    'new_info_01 = info.strip()print(new_info_01)# >>> Jack is a good boynew_info_02 = info.strip(info)print(new_info_02)print(len(new_info_02))# >>>   实际上这里的 'new_info_02' 已经北清空了# >>> 0 清空后的 'new_info_02' 长度为0text = 'abcde'text_lstrip = text.lstrip('a')print(text_lstrip)# >>> bcdetext_rstrip = text.rstrip('e')print(text_rstrip)# >>> abcd

replace()函数

replace()函数的功能:把字符串中的 old(旧字符串) 替换成 new(新字符串),并可以指定数量,默认 -1 代表替换全部

replace()函数的用法:str = string.replace(old, new, max)

  • old :被替换的元素
  • new:替换 old 的元素
  • max:可选,代表替换几个,默认替换掉全部匹配到的 old 。

示例如下:

info = "hello, Neo"print(info.replace("Neo", "Jack"))print(info.replace(" ", "*", 1))# >>> hello, Jack# >>> hello,*Neoinfo_test = "hello world !!!"new_info_01 = info_test.replace("h", "H")new_info_02 = new_info_01.replace("w", "W")print(new_info_02.replace('!!!', 'Python'))# >>> Hello World Python

join() 函数

join()函数的功能:将序列中的元素以指定的字符连接生成一个新的字符串

join()函数的用法:str = "".join(lists)

示例如下:

lists = ["a", "b", "c"]tuples = ("1", "2", "3")print("*".join(lists))# >>> a*b*cprint("@".join(tuples))# >>> 1@2@3

知识点

  • “”.join(lists) 是常见的将列表、元组转成字符串的写法
  • 列表里面只能存放字符串元素,有其他类型的元素会报错 TypeError: sequence item 0: expected str instance, int found
  • 元组也能传进去

split() 函数

split()函数的功能:将字符串按照str分割成列表,如果参数 num 有指定值,则分隔 num+1 个子字符串

split()函数的用法:str = string.split() ,括号内可以指定分隔符

使用空格将字符串分割为多个单词,返回一个列表,示例如下:

info = 'Hello World Python Is Good'print(info.split(" "))# >>> ['Hello', 'World', 'Python', 'Is', 'Good']print(info.split(" ", 1))# >>> ['Hello', 'World Python Is Good']

缺省情况下,使用空格将字符串分割为多个单词,可以在 split () 方法中指定分隔符,示例如下:

info = 'Hello World:Python Is_Good'print(info.split(":"))# >>> ['Hello World', 'Python Is_Good']

字符串中返回 bool 类型的函数集合

之所以说它是集合,是因为我们有多个函数返回的是 bool 类型,接下来我们看看都有哪些函数返回的是 bool 类型。

isspace() 函数

isspace() 函数的功能:判断字符串是否是一个由空格组成的字符串

isspace() 函数的用法:isspace_bool_type = string.isspace() ,无参数可传,返回一个 bool 类型

示例如下:

string = ' 'print(string.isspace())# >>> Truenew_string = 'hello world'print(new_string.isspace())# >>> False虽然 'hello world' 中有一个空格,但是除了空格之外,还有其他字符,所以返回 False

附:这里需要注意一点,由空格组成的字符串不等于空字符串,因为空格也占用一个长度。

istitle() 函数

istitle()函数的功能:判断字符串是否是一个标题类型 (即多个单词,首字母都是大写)

istitle()函数的用法:istitle_bool_type = string.istitle() ,无参数可传,返回一个 bool 类型

示例如下:

info_01 = 'Hello Jack'info_02 = 'hello jack'print(info_01.istitle())# >>> Trueprint(info_02.istitle())# >>> False

附:需要注意的是该函数只能对英文有效

isupper() 函数 与 islower() 函数

功能:

  • isupper() 函数 判断字符串中的字符是否都是大写
  • islower() 函数 判断字符串中的字符是否都是小写

用法:

  • isupper_bool_type = string.isupper() ,无参数可传,返回一个 bool 类型
  • islower_bool_type = islower(),无参数可传,返回一个 bool 类型

示例如下:

text_01 = 'GOOD BYE'print(text_01.isupper())# >>> Trueprint(text_01.islower())# >>> False

附:这里需要注意的是, isupper() 函数 与 islower() 函数 只检测字符串里的字母,对其他字符不做判断