Python 程序设计——day7——字符串

目录

一、字符串的用法

1、输入与输出

2、下标(索引)

3、切片

二、字符串的常用操作

1、查找

(1)find( ) 函数

(2)index( ) 函数

(3)count( ) 函数

(4)rfind( ) 函数

(5)rindex( ) 函数

2、修改

(1)replace( ) 函数

(2)split( ) 函数

(3)join( )函数

(4)大小写转化

① capitalize( ) 函数

 ② title( ) 函数

 ③ upper( ) 函数

 ④ lower( ) 函数

 ⑤ lstrip( ) 函数

⑥ rstrip( ) 函数

 ⑦ strip( ) 函数

 ⑧ just( ) 函数

3、判断

(1)startswith( ) 函数

 (2)endswith ( ) 函数

 (3)isalpha( ) 函数

 (4)isdigit( ) 函数

 (5)isalnum( ) 函数

 (6)isspace( ) 函数

三、字符串的运算


        字符串是 Python 中最常用的数据类型。我们可以使用 ' ' 或 " " 来创建字符串,引号必须是英文输入法,另外三引号也可以创建字符串,但是很少用到,更多是作为多行注释来用。创建字符串很简单,只要为变量分配一个值即可

一、字符串的用法

1、输入与输出

        前文有详细的介绍,需要的话可以点击链接再看一下:Python程序设计——day3——输入输出、转义字符与数据类型转化_竹林长老的博客-CSDN博客  https://blog.csdn.net/cumt_zhj/article/details/131452926?spm=1001.2014.3001.5502

        这里可以简单再回顾一下格式化输出:

示例:

name = "张译"
age = 45
height = 1.78
print("我的名字是%s"%name)
print("我今年%d岁了"%age)
print("我的身高是%.1f米"%height)
print("大家好,我叫{},我今年{}岁,我的升高是{}米".format(name,age,height))
print(f"大家好,我叫{name},我今年{age}岁,我的升高是{height}米")

运行结果:

# 我的名字是张译
# 我今年45岁了
# 我的身高是1.8米
# 大家好,我叫张译,我今年45岁,我的升高是1.78米
# 大家好,我叫张译,我今年45岁,我的升高是1.78米

2、下标(索引)

        “下标” ⼜叫 “索引” ,就是编号。比如读者想找一本手中书籍的同类数,就可以根据手中书籍的编号,按照图书馆分区分类摆放的规则迅速找到自己想要的书籍。所以编号的作用就是快速找到对应的位置与信息

注意:索引是从0开始的

示例:

str1 = 'hello,world'
print(str1[0:6])      # 运行结果:hello, /\ 后面的数字所代表的位置取不到
print(str1[1:])       # 运行结果:ello,world /\ : 后面没有数字(下标)代表取到最后
print(str1[:5])       # 运行结果:hello /\ : 后面有数字,代表从0开始,下表为5结束(不会拿到本身)
print(str1[:])        # 运行结果:hello,world /\ : 前后都没数字,默认取全部

3、切片

        切片是在索引的基础上增加了一个步长的概念,也是指截取操作对象部分内容的操作。字符串、列表和元组都支持切片操作

注意:截取内容不包括结束位置下标对应的数据,下标一般取0到正整数

           步长是选取间隔,正负整数均可取,默认步长为1 

示例:

str1 = 'hello,world'
print(str1)      # 运行结果:hello,world /\ 等同于print(str1[:]),全拿内部元素,可以给设置步长
print(str1[::2])  # 运行结果:hlowrd /\ 第一个:前后无数字代表取全部,:加数字代表步长取值
print(str1[:-1])   # 运行结果:hello,worl /\ 从0开始,到最后一个数结束(-1代表最后一个数,取不到-1)
print(str1[::-1])   # 运行结果:dlrow,olleh /\ 从-1开始,倒着打印字符串,步长为1
print(str1[::-2])   # 运行结果:drwolh /\ 从-1开始,倒着打印字符串,步长为2
print(str1[-4:-1])   # 运行结果:orl /\ 从倒数第四个开始,到倒数第一个结束(不包含-1本身)
print(str1[:-4:-1])   # 运行结果:dlr /\ 从最后一个开始,到倒数第4个结束(取不到倒数第4个)
print(str1[11:0:-1])  # 运行结果:: dlrow,olle /\ 反转后取不到最前面,此处为1-11的反转
print(str1[11::-1])   # 运行结果:: dlrow,olleh /\ 反转后可以取到到最前面

二、字符串的常用操作

        字符串的常用操作方法有查找修改判断三大类

1、查找

        所谓字符串查找⽅法即是查找元素在字符串中的位置或出现的次数,主要包括 find( ) 函数、index( ) 函数、count( ) 函数、rfind( ) 函数和 rindex( ) 函数等

(1)find( ) 函数

        检测某个元素是否包含在这个字符串中,如果在,返回这个字符开始的位置下标,否则则返回-1

用法:

        字符串序列.find ( 子字符串或其他字符串, 开始位置下标, 结束位置下标 )

示例:

str1 = 'hello python and world'
str2 = 'll'
str3 = 'lll'
print(str1.find('o'))             # 运行结果:4   
print(str1.find(str2))            # 运行结果:2
print(str1.find(str3))            # 运行结果:-1
print(str1.find(str2,2,10))       # 运行结果:2 
print(str1.find(str2,8,11))       # 运行结果:-1 

注意:开始和结束位置下标可以省略,表示在整个字符串序列中查找

(2)index( ) 函数

        检测某个元素是否包含在这个字符串中,如果在返回这个开始的位置下标,否则则报异常。相对而言 index 用得更多一些

示例:

str1 = 'hello python and world'
str2 = 'll'
str3 = 'lll'
print(str1.index('o'))               # 运行结果:4 
print(str1.index(str2))              # 运行结果:2
print(str1.index(str2,2,10))         # 运行结果:2
print(str1.index(str3))              # 运行结果:异常
print(str1.index(str2,8,11))         # 运行结果:异常

注意:开始和结束位置下标可以省略,表示在整个字符串序列中查找

(3)count( ) 函数

        返回某个元素在字符串中出现的次数

用法

        字符串序列.count( 子字符串或其他字符串, 开始位置下标, 结束位置下标 ) 

示例:

str1 = 'hello python and world'
str2 = 'l'
str3 = 'll'
print(str1.count('o'))               # 运行结果:3
print(str1.count(str2))              # 运行结果:3
print(str1.count(str2,2,10))         # 运行结果:2
print(str1.count(str3))              # 运行结果:1
print(str1.count(str2,8,11))         # 运行结果:0

注意:开始和结束位置下标可以省略,表示在整个字符串序列中查找

(4)rfind( ) 函数

        和 find( ) 功能相同,但查找⽅向为右侧开始,查找结果的下标也就是从右侧开始算起

(5)rindex( ) 函数

        和 index( ) 功能相同,但查找⽅向为右侧开始,查找结果的下标也就是从右侧开始算起

2、修改

        对字符串当中的内容进行修改

(1)replace( ) 函数

        替换内容

用法

        字符串序列.replace( 旧子字符串, 新子字符串, 替换次数 ) 

示例:

str1 = 'hello python and hello world'
print(str1.replace('hello','hi'))       # 运行结果:hi python and hi world
print(str1.replace('hello','hi',1))     # 运行结果:hi python and hello world

注意:

  • 替换次数如果超出子字符串出现次数,则替换次数为该子字符串出现次数
  • 数据按照是否能直接修改分为可变类型不可变类型两种。字符串类型的数据修改的时候不能改变原有字符串,属于不能直接修改数据的类型即是不可变类型

(2)split( ) 函数

        按照指定字符分割字符串

用法

        字符串序列.split( 分割字符, 分割字符出现次数 )

示例:

str1 = 'hello python and hello world'
print(str1.split('and'))            # 运行结果:['hello python ', ' hello world']
print(str1.split('hello',1))        # 运行结果:['', ' python and hello world']
print(str1.split('hello',2))        # 运行结果:['', ' python and ', ' world']

注意:分割完成之后他会返回一个列表,分割字符被  '  '  取代 

(3)join( )函数

        ⽤⼀个字符合并并隔开字符串或多个字符串(数字不可以)组成的序列,即是将多个字符串合并为⼀个新的字符串

用法

        字符.join( 字符串 或 多字符串组成的序列 )

示例:

str1 = 'hello, world'
print('+'.join(str1))       # h+e+l+l+o+,+ +w+o+r+l+d
print(' '.join(str1))       # h e l l o ,   w o r l d

li1 = ["hello", "python", "and", "hello", "world"]
t1 = ("hello", "python", "and", "hello", "world")
set1 = {"hello", "python", "and", "hello", "world"}
print("__".join(li1))       # 将列表转化为字符串,并且使用指定符号隔开
print(",".join(t1))         # 将元组转化为字符串,并且使用指定符号隔开
print("|".join(set1))       # 将集合转化为字符串,并且使用指定符号隔开

运行结果:

# hello__python__and__hello__world
# hello,python,and,hello,world
# python|world|and|hello

注意:集合内的元素是无序的,所以每次打印的结果可能都不一样,这也是集合在 Python 中使用频率较低的原因

(4)大小写转化

        Python 中有时会需要对字符串中字母的大小写进行转化,使用频率较低,了解即可

① capitalize( ) 函数

        将字符串第⼀个字符转换成大写

示例:

str1 = 'hello python and hello world'
print(str1.capitalize())    # 运行结果:Hello python and hello world
 ② title( ) 函数(掌握)

        将字符串每个单词首字母转换成大写

示例:

str1 = 'hello python and hello world'
print(str1.title())    # 运行结果:Hello Python And Hello World
 ③ upper( ) 函数(掌握)

        将字符串中小写转大写

示例:

str1 = 'hello python and hello world'
print(str1.upper())    # 运行结果:HELLO PYTHON AND HELLO WORLD
 ④ lower( ) 函数(掌握)

        将字符串中大写转小写

示例:

str1 = 'Hello Python and Hello World'
print(str1.lower())    # 运行结果:hello python and hello world
 ⑤ lstrip( ) 函数

        删除字符串左侧空⽩字符

示例:

str1 = '   Hello Python and Hello World'
print(str1.lstrip())    # 运行结果:Hello Python and Hello World
⑥ rstrip( ) 函数

        删除字符串右侧空⽩字符

示例:

str1 = 'Hello Python and Hello World   '
print(str1.rstrip())    # 运行结果:Hello Python and Hello World
 ⑦ strip( ) 函数(重点掌握)

        删除字符串两侧空⽩字符

示例:

str1 = '  hello python and hello world  '
print(str1.capitalize())    # 运行结果:Hello python and hello world
 ⑧ just( ) 函数

        填充字符串

用法:

  •         字符串序列.ljust(⻓度, 填充字符)(左对齐)
  •         字符串序列.rjust(⻓度, 填充字符)(左对齐)
  •         字符串序列.center(⻓度, 填充字符)(左对齐)

示例:

str = "Hello"
print(str.ljust(10,","))	# 左对齐:Hello,,,,,
print(str.rjust(10,","))	# 右对齐:,,,,,Hello
print(str.center(10,","))	# 居中对齐:,,Hello,,,

3、判断(了解即可)

(1)startswith( ) 函数

        检查字符串是否是以指定元素开头

语法 :

        字符串序列.startswith(⼦串, 开始位置下标, 结束位置下标)

示例:

str = 'hello python and hello world'
print(str.startswith('hello'))          # 运行结果:True
print(str.startswith('and'))            # 运行结果:False
print(str.startswith('and',13))         # 运行结果:True
print(str.startswith('hello',0,10))     # 运行结果:True
 (2)endswith ( ) 函数

        检查字符串是否是以指定元素结尾

示例:

str = 'hello python and hello world'
print(str.endswith('world'))          # 运行结果:True
print(str.endswith('and'))            # 运行结果:False
print(str.endswith('hello',0,5))      # 运行结果:True
 (3)isalpha( ) 函数

        如果字符串所有字符都是字⺟则返回 True, 否则返回 False

示例:

s1 = 'hello'
s2 = 'hello 世界'
print(s1.isalpha())		# 运行结果:True
print(s2.isalpha())		# 运行结果:False
 (4)isdigit( ) 函数

        如果字符串只包含数字则返回 True 否则返回 False

示例:

s1 = '12345'
s2 = 'hello123'
print(s1.isdigit())		# 运行结果:True
print(s2.isdigit())		# 运行结果:False
 (5)isalnum( ) 函数

        如果字符串所有字符都是字⺟或数字则返 回 True,否则返回False

示例:

s1 = '12345'
s2 = 'hello123'
s3 = 'hello 123'
s4 = 'hello 世界'
print(s1.isalnum())		# 运行结果:True
print(s2.isalnum())		# 运行结果:True
print(s3.isalnum())		# 运行结果:False,有空格都不行
print(s4.isalnum())		# 运行结果:False
 (6)isspace( ) 函数

        如果字符串中只包含空⽩,则返回 True,否则返回 False

示例:

s1 = 'h e l l o'
s2 = '    '
print(s1.isspace())		# 运行结果:False
print(s2.isspace())		# 运行结果:True

三、字符串的运算

a = "Hello", b = "world"

运算符作用运算过程运算结果
+连接字符串a + b'Hello world'
[ ]通过索引获取字符串中字符a[2]'l'
[ : ]截取字符串中的一部分,切片a[1:5]'ello'
in成员运算符 - 如果字符串中包含给定的字符返回 True'e' in aTrue
not in成员运算符 - 如果字符串中不包含给定的字符返回 True'b' not in aTrue
r取消转义r'hi \n haha''hi \n haha'
%格式字符串%s %d %f

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值