字符串(上课版笔记)

50 阅读7分钟

字符串定义

什么是字符串

被'' "" """ """ 包裹的数据 咱们就称为字符串数据

且不管单双引号还是三引号 都要成对的出现

字符串的输入输出

a = 1
name1 = 'name'
name2 = "name"
name3 = """    name
                        你好"""
print(name1,name2,name3)
print(type(name1),type(name2),type(name3))
print('name1')

输入input()

name = input("请输入你的名字:")
print(type(name))
age = input("请输入你的年龄:")
print(type(age))

访问字符串中的值

a = 'hellopython'
# h e l l o p y t h o n
# 0 1 2 3 4 5 6 7 8 9 10 #下标 索引 python中的下标从0开始!!!!!
             -4-3 -2 -1
print(a[-4:-3:-2])

#需求:在字符串中拿到第二个h #通过索引进行取值 a[下标] print(a[8]) print(a[-3])

需求

我要拿到python这一段值

通过切片进行取值 a[起始值索引:终止值索引:步长]

步长默认为1

终止值索引:左闭右开 不写 默认到结尾

起始值:默认为0 可以更改

字符串的切片

print(a[::-1]) #逆序输出
print(a[0:5]) #从大到小切
print(a[1:10]) #从1开始,到10结束(不会拿到10本身)
print(a[6:12])
print(a[6:12:2]) #从6开始,到12结束 步长为2(不会拿到12本身)
print(a[:5])  #从0开始,下表为5结束(不会拿到本身)
print(a[5:])  #从5开始,一直到结束
print(a[:])   #拿取所有
print(a[::2]) #从0开始,步长为2,拿取所有

print(a[-1]) #从右到左从-1开始
print(a[:-1])  #从0开始,到最后一个人结束(-1代表最后一个数,不包含-1本身)左闭右开 最右一个拿不到
print(a[-3:])
print(a[-1:-4]) #从小到大切
print(a[::-1]) #从右往左拿取全部
print(a[:-4:-1])
print(a[-5:-9:-1]) #取值的方向与步长的方向不一致 导致取不到值
### print(a[5:0:-1])
print(a[0:10:-1])

字符串的常用操作方法

查找 find()

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

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

var = "hello and python and hello world "
print(var.find("and"))  #查找到and首字母下标
print(var.find("and",8,20)) #查找到下标为8-20,and首字母下标
print(var.find("ors")) #查找or,如果没有,则返回-1

index()

检测某个⼦串是否包含在这个字符串中,如果在返回这个⼦串开始的位置下标,否则则报异常。

# var = "hello and python and hello world"
# print(var.index("and"))          # 查找到and首字母下标
# print(var.index("and",8,20))     # 查找到下标为8-20,and首字母下标
# print(var.index("ors"))          # 查找ors,如果没有,则报错

count()

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

语法

lstr.count(str,start=0,end=len(lstr))

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

# var = "hello and python and hello world"
# print(var.index("and"))          # 查找到and首字母下标
# print(var.index("and",8,20))     # 查找到下标为8-20,and首字母下标
# print(var.index("ors"))          # 查找ors,如果没有,则报错

# li = [1,2,3,4,5,[1,2,3,4,5]]  #[]整体
# print(li.count(1))
# print(li[-1].count(1))  #[[]]找

拓展(了解即可)

var = "hello and python and hello world"

rfind():

和find()功能相同,但查找⽅向为右侧开始。

print(var.rfind("and"))

rindex()

和index()功能相同,但查找⽅向为右侧开始。

print(var.rindex("and"))

**修改 replace() ** ▲很重要

语法: 含义:对字符串当中的内容进行修改 字符串序列.replace(旧⼦串, 新⼦串, 替换次数)

var = "hello and python and hello world"
newstr = var.replace("and","和")  # 将里面所有的and替换为和
print(newstr,id(newstr))

# print(var.replace("and","和",1))     # 将and替换为和,只替换一次
#**注意:替换次数如果超出⼦串出现次数,则替换次数为该⼦串出现次数。**

#replace替换中间的还不能 可用其他办法 split分割获得下标替换或删除

print(var,id(var)) #没有改变原来的字符串的

数据类型中的可变与不可变数据类型

可变的:

不可变的: 数值 字符串

split() 分割

var = "hello and python and hello world"
print(var.split("and"))         # 以and为界,分隔开其他字符串,返回一个列表
print(var.split("and",1))       # 以and为界,分隔开其他字符串,只分割一次,返回一个列表
print(var.split(" "))

join() 连接

用一个字符或子串合并字符串,即是将多个字符串合并为一个新的字符串。

语法: 'sep'.join(iterable) 参数说明 sep:分隔符。可以为空

seq:要连接的元素序列、字符串、元组、字典

上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串

返回值:返回一个以分隔符sep连接各个元素后生成的字符串

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

list1 = ["hello", "python", "i", "love", "you"]
t1 = ("hello", "python", "i", "love", "you")
set1 = {"hello", "python", "i", "love", "you"}
print("__".join(list1))     # 将列表转化为字符串,并且使用指定符号隔开
print(",".join(t1))         # 将元组转化为字符串,并且使用指定符号隔开
print("|".join(set1))       # 将集合转化为字符串,并且使用指定符号隔开
a ='12345678'
print('_'.join(a)) #iterable可迭代对象  字符串中的方法

能够从序列中一个一个的取出数据的 能够使用循环遍历的就肯定是一个可迭代对象

li = ['1','2','3','4','5']
print(''.join(li))

删除 strip()

rstrip() 右侧
lstrip() 左侧

var = "@hello and python @@and$ hello world@@"
print(var.strip())  #删除两侧空格
print(var.strip('@'))  #删除指定的字符串 字符串左右两边的 中间是不能直接删除的
print(var.replace('@','').replace('$','')) #正则表达式

了解即可

isxxx() 自省

isalpha():如果字符串所有字符都是字⺟则返回 True, 否则返回 False。

mystr1 = 'hello'
mystr2 = 'hello12345'

print(mystr1.isalpha())       # 结果:True
print(mystr2.isalpha())       # 结果:False

isdigit():如果字符串只包含数字则返回 True 否则返回 False。

mystr1 = 'aaa12345'
mystr2 = '12345'

print(mystr1.isdigit())       # 结果: False
print(mystr2.isdigit())       # 结果:False

isalnum():如果字符串所有字符都是字⺟或数字则返 回 True,否则返回False。

mystr1 = 'aaa12345'
mystr2 = '12345-'

print(mystr1.isalnum())       # 结果:True
print(mystr2.isalnum())       # 结果:False

isspace():如果字符串中只包含空⽩,则返回 True,否则返回 False。

mystr1 = '1 2 3 4 5'
mystr2 = ' '

print(mystr1.isspace())       # 结果:False
print(mystr2.isspace())       # 结果:True

其他方法

startswith():检查字符串是否是以指定⼦串开头

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

var = "hello and python and hello world"

print(var.startswith("hello"))       # 开头是hello,返回True
print(var.startswith("and"))         # 开头不是and,返回False
print(var.startswith("and",6,20))     # 在索引6-20,开头是and,返回True

endswith():检查字符串是否是以指定⼦串结尾

var = "hello and python and hello world"

print(var.endswith("and"))          # 结尾不是and,返回False
print(var.endswith("world"))         # 结尾时world,返回True
print(var.endswith("and",0,9))       # 在0到9的索引范围,是and结尾,返回True

capitalize():将字符串第⼀个字符转换成⼤写。

var = "hello and python and hello world"

print(var.capitalize())          # 将字符串第⼀个字符转换成⼤写。

title():将字符串每个单词⾸字⺟转换成⼤写。

var = "hello and python and hello world"

print(var.title()) # 将字符串每个单词⾸字⺟转换成⼤写。

upper():将字符串中⼩写转⼤写。

var = "hello and python and hello world"

print(var.upper())          # 将字符串中⼩写转⼤写。

lower():将字符串中⼤写转⼩写。

var = "hello and python and hello world"

print(var.lower())          # 将字符串中⼤写转⼩写。

不常用

ljust():返回⼀个原字符串左对⻬,并使⽤指定字符(默认空格)填充⾄对应⻓度 的新字符串

rjust():返回⼀个原字符串右对⻬,并使⽤指定字符(默认空格)填充⾄对应⻓度 的新字符串

center():返回⼀个原字符串居中,并使⽤指定字符(默认空格)填充⾄对应⻓度 的新字符串

字符串运算

a = "Hello",b = "Python"

+字符串连接>>>a + b'HelloPython'
[]通过索引获取字符串中字符>>>a[1]'e'
[ : ]截取字符串中的一部分>>>a[1:4]'ell'
in成员运算符 - 如果字符串中包含给定的字符返回 True>>>"H" in aTrue
not in成员运算符 - 如果字符串中不包含给定的字符返回 True>>>"M" not in aTrue
r取消转义>>>r“你\n好”你\n好
%格式字符串

r 转义

print(r'你\n好呀')
print('你\n好呀')
print(r'你\n好呀') #特殊字符  \n \t \r . * ?  将原有的特殊字符转成普通字符