20230409-Python-字符串-day6

发布时间 2023-04-09 23:52:56作者: xiao智

字符串

4月9

字符串是python中最常见的数据类型,我们可以使用单引号 ' ' 、 双引号 " " 、三引号 """ """ 来创建字符串,只要为变量分配一个值即可

#单引号
var1 = 'hello word'

#双引号
var2 = "hello Python"

#三引号,可以换行,如果没有变量名,这就是一个多行注释
var3 = """ this is Python,
I lova Python"""

print(var1)
print(var2)
print(var3)

字符的输入输出

格式化输出

name = "yuwen"
age = 20
height = 175

print("我叫%s" % name)
print("今年 %d 岁" % age)
print("身高 %.2f cm" % height)
print("大家好,我叫{},身高{},年龄{}".format(name, age, height))
print(f"大家好,我叫{name},今年{age},身高{height}")

输入input()

>>> name =  input("请输入你的名字:")
请输入你的名字:yuwem
>>> print(name)
yuwem

>>> age = input("请输入你的年龄:")
请输入你的年龄:20
>>> print(age)
20

下标(索引)

下标 又叫 索引 就是编号。比如说火车座位号,座位号的作用:按照编号找到对应的座位

var = "hello word"
print(var[0])
print(var[1])
print(var[2])

#输出结果
>>>h
>>>e
>>>l

切片

切⽚是指对操作的对象截取其中⼀部分的操作。字符串、列表、元组都⽀持切⽚操作

  • 不包含结束位置下标对应的数据, 正负整数均可;
  • 步⻓是选取间隔,正负整数均可,默认步⻓为1。
name = "hello word"
print(name[2:5])        #从索引2开始,到5结束,不会拿到本身
print(name[2:5:1])      #从索引2开始,到5结束,步长为1,不会拿到本身
print(name[:5])         #从索引0开始一直到5,不会拿到本身
print(name[1:])         #从索引1开始一直到结束
print(name[:])          #取所有
print(name[::2])        #从索引0开始,取所有,步长为2
print(name[:-1])        #从索引0开始,到最后一个数结束,-1代表最后一个数,不包含-1本身
print(name[-4:-1])      #从倒数第四个开始,到倒数第一个结束,不包含-1本身
print(name[::-1])       #从-1开始,倒着打印字符串,步长为1
print(name[::-2])       #从-2开始,倒着打印字符串,步长为2
print(name[:-4:-1])     #从-1开始,倒着打印字符串,一直到-4,不包含-4本身,步长为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("yuwen"))         # 查找"yuwen",没有返回-1

#输出结果
6
17
-1
  • index():检测某个字符串是否包含这个字符串中,如果在,返回字符在字符串中的下标位子,否则报异常

语法

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

# 字符串序列.index(⼦串, 开始位置下标, 结束位置下标)
var = "hello and python and hello world"

print(var.index("and"))
print(var.index("and", 8, 20))
print(var.index("yuwen"))		# 查找ors,如果没有,则报错


#输出结果
   print(var.index("yuwen"))
ValueError: substring not found
6
17
  • count():返回某个字符串在,字符串序列中出现的次数。

语法

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

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

var = "hello and python and hello world"
print(var.count("and"))       #查找and在字符串序列中,出现的次数
print(var.count("ands"))      #如果没有,则返回0次
print(var.count("and",8,20))  #指定区间中,查找and字符出现的次数


#输出结果
2
0
1
  • **rfind(): ** find()功能相同,但查找⽅向为右侧开始。
  • rindex():index()功能相同,但查找⽅向为右侧开始。
var = "hello and python and hello world"

# rfind(): 和find()功能相同,但查找⽅向为右侧开始。
print(var.rfind("and"))
print(var.rfind("ands"))

# rindex():和index()功能相同,但查找⽅向为右侧开始。
print(var.rindex("and"))
print(var.rindex("ands"))

修改

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

  • repalec(): 替换内容

语法

注意:替换次数如果超出⼦串出现次数,则替换次数为该⼦串出现次数。

var = "hello and python and hello world"

print(var.replace("and","abc"))     #默认替换所有配置的字符
print(var.replace("and","abc",1))   #将and替换为和,只替换一次


#输出结果
hello abc python abc hello world
hello abc python and hello world

注意:数据按照是否能直接修改分为可变类型不可变类型两种。字符串类型的数据修改的时候不能改变原有字符串,属于不能直接修改数据的类型即是不可变类型。

修改后内存地址没有发生变化 :

可变类型 --没有变化

不可变类型 --地址变量

  • split():按照指定的字符分割字符串

语法

注意:num表示的是分割字符出现的次数

var = "hello and python and hello world"

print(var.split("and"))     #以and为界,分隔开其他字符串,并且返回一个数组
print(var.split("a",1))       #以a为界,分隔开其他字符串,只分割一次,返回一个数组


#输出结果
['hello ', ' python ', ' hello world']
['hello ', 'nd python and hello world']
  • join():用一个字符或者字符串合并,即将多个字符串合并为一个新的字符串

语法:

list1 = ['hello', 'and', 'python', 'and', 'hello', 'world']
tuple1 = ('hello', 'and', 'python', 'and', 'hello', 'world')
set1 = {'hello', 'and', 'python', 'and', 'hello', 'world'}

print("_".join(list1))
print(",".join(tuple1))
print("|".join(set1))


#输出结果
hello_and_python_and_hello_world		 # 将列表转化为字符串,并且使用指定符号隔开	
hello,and,python,and,hello,world		 # 将元组转化为字符串,并且使用指定符号隔开
and|world|hello|python					 # 将集合转化为字符串,并且使用指定符号隔开

大小写转换

  • capitalize():将字符串第⼀个字符转换成⼤写。
  • title():将字符串每个单词⾸字⺟转换成⼤写。
  • upper():将字符串中⼩写转⼤写。
  • lower():将字符串中⼤写转⼩写。
  • lstrip():删除字符串左侧空⽩字符。 了解即可
  • rstrip():删除字符串右侧空⽩字符。 了解即可
  • strip():删除字符串两侧空⽩字符。
var = "  hello And pyThon aNd hello world  "


print(var.capitalize())         #将字符串第一个字大写
print(var.title())              #将字符串单词首字母大写
print(var.upper())              #将字符串全部大写
print(var.lower())              #将字符串全部小写
print(var.lstrip())             #删除字符串左侧空白
print(var.rstrip())             #删除字符串右侧空白
print(var.strip())              #删除字符串量测空白


#输出结果
  hello and python and hello world  
  Hello And Python And Hello World  
  HELLO AND PYTHON AND HELLO WORLD  
  hello and python and hello world  
hello And pyThon aNd hello world  
  hello And pyThon aNd hello world
hello And pyThon aNd hello world
  • ljust():返回⼀个原字符串左对⻬,并使⽤指定字符(默认空格)填充⾄对应⻓度 的新字符串
  • rjust():返回⼀个原字符串右对⻬,并使⽤指定字符(默认空格)填充⾄对应⻓度 的新字符串
  • center():返回⼀个原字符串居中,并使⽤指定字符(默认空格)填充⾄对应⻓度 的新字符串
var = "hello"

print(var.ljust(10,"_"))		#左对齐
print(var.rjust(10,"_"))		#右对齐
print(var.center(10,"_"))		#居中对齐


#输出结果
hello_____
_____hello
__hello___

判断

  • 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
  • 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

字符串运算

a = "Hello",b = "Python"

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