新西兰服务器

Python字符串的常用方法实例分析


Python字符串的常用方法实例分析

发布时间:2022-03-05 19:04:52 来源:高防服务器网 阅读:77 作者:iii 栏目:开发技术

这篇文章主要介绍“Python字符串的常用方法实例分析”,在日常操作中,相信很多人在Python字符串的常用方法实例分析问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Python字符串的常用方法实例分析”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

什么是对象

对于 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  # >>> False    string_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 boy    new_info_02 = info.strip(info)  print(new_info_02)  print(len(new_info_02))    # >>>          实际上这里的 'new_info_02' 已经北清空了  # >>> 0        清空后的 'new_info_02' 长度为0    text = 'abcde'  text_lstrip = text.lstrip('a')  print(text_lstrip)    # >>> bcde    text_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,*Neo    info_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*c  print("@".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())  # >>> True    new_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())    # >>> True  print(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())    # >>> True  print(text_01.islower())    # >>> False

到此,关于“Python字符串的常用方法实例分析”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注高防服务器网网站,小编会继续努力为大家带来更多实用的文章!

[微信提示:高防服务器能助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。

[图文来源于网络,不代表本站立场,如有侵权,请联系高防服务器网删除]
[