【小白讲python】七、字符串操作

一、引入

当我们进行Python编程时,字符串是常用的数据类型之一。它们不仅可以存储文本信息,还可以进行各种操作和处理。在本篇博客中,我们将介绍Python中一些常用的字符串操作,帮助你更好地理解和使用字符串。

(1)字符串基础

首先,我们需要了解如何定义字符串。在Python中,我们可以使用单引号或双引号来定义一个字符串变量。例如:

str1 = 'Hello World'
str2 = "I'm learning Python"
  • str1包含了字符串’Hello World’,
  • 而str2包含了字符串"I’m learning Python"。
  • 同时,我们也可以将字符串赋值给变量,并对其进行操作和处理。
    ##字符串的输入输出
1、格式化输出
name = "小白讲python"
age = 20
heigth = 180.5

print("我的名字是%s"%name)
print("我今年%d岁了"%age)
print("我的身高是%.2f"%heigth)
print("大家好,我叫{},我今年{}岁,我的身高是{}".format(name,age,heigth))
print(f"大家好,我叫{name},我今年{age}岁,我的升高是{heigth}")

后面的都可以正确输出

2、输入input()
name = input("请输入你的名字:")
>>>"小白讲python"
>>>print(type(name)) # 输出为 str
>>>age = input("请输入你的年龄:")
>>>18
>>>print(type(age)) # # 输出为 str

由此可得,input输入的都为字符串
input输入的都为字符串
input输入的都为字符串

3、下标/索引

Python中的字符串是一个序列(Sequence),这意味着我们可以用索引来访问每个字符。在Python中,索引从0开始,因此第一个字符的索引为0,第二个字符的索引为1,以此类推。例如:

s = 'Python'
print(s[0]) # 输出 'P'
print(s[1]) # 输出 'y'
4、切片

通过索引,我们可以获取一个字符串中某些部分的子串,操作方法称为切片(Slicing)。
-切片的语法形式为:[start:stop:step]。

  • start表示起始索引(包含),
  • stop表示结束索引(不包含),
  • step表示步长(默认为1)。
    例如:
name = "hello,world"
print(name[2:5])    # 从2开始,到5结束(不会拿到5本身)
print(name[2:5:1])  # 从2开始,到5结束,步长为1(不会拿到5本身)
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])   # 从-1开始,倒着打印字符串,步长为2

(2)字符串的常用操作

1、查找

(1)find()

**概述:**用于在字符串中查找子字符串,返回找到的第一个子字符串的起始位置。如果没有找到子字符串,则返回-1
用法:

str.find(sub[, start[, end]])

使用
下面是一个使用 find() 方法的例子:

str1 = "Hello, world!"
str2 = "world"

# 查找子字符串 "world"
index = str1.find(str2)
if index != -1:
    print(f"{str2}{str1} 中的位置是 {index}")
else:
    print(f"{str2} 不在 {str1} 中")

输出结果为

world 在 Hello, world! 中的位置是 7
(2)index()

字符串的 index() 方法用于查找子字符串在原字符串中的位置,并返回其起始位置。如果子字符串不在原字符串中,则会抛出 ValueError 异常。

index() 方法的语法为:

str.index(sub[, start[, end]])

其中

  • sub 参数表示要查找的子字符串,
  • start 和 end 表示查找的起始位置和终止位置,可选。
    与 find() 方法类似,index() 方法也是用于查找字符串中的子字符串,并返回其所在的位置。
    不同的是
    如果查找的子字符串在原字符串中不存在,则 index() 方法会抛出 ValueError 异常。
  • 我们有一个字符串 var1 = “hello world”,想要查找其中的子字符串 “world”,可以使用以下代码实现:
var1 = 'hello world'
index = var1.index('world')
print(index)

输出结果为6
在字符串 var1 中,不存在子字符串 “binjie09”,所以会抛出 ValueError 异常。

(3)count()

用于返回一个字符串中指定子串出现的次数。它的语法如下:

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

其中

  • sub 表示要在原字符串中查找的子串,
  • start 和 end 是可选参数,表示查找的起始位置和终止位置。
    如果不传入 start 和 end,则默认从字符串的开始到结束进行查找。
    我们来看一个例子:
sentence = "The quick brown fox jumps over the lazy dog."
count = sentence.count("the")
print(count)

输出结果为 1,

  • 因为在 sentence 中只有一个 “the” 出现了一次。但是,如果我们将字符串全都转换成小写再进行计数,如下所示:
sentence = "The quick brown fox jumps over the lazy dog."
count = sentence.lower().count("the")
print(count)

此时输出结果为 2,因为这样就可以捕获到大小写不同的 “The” 和 “the”。
需要注意的是,

  • count() 方法是区分大小写的。
  • 如果要进行不区分大小写的计数,需要将字符串先全部转化为大写或小写,再进行 count() 计数。
  • 另外,如果子串没有在原字符串中出现过,那么 count() 方法的返回值为 0。
    总之,count() 方法是 Python 中非常实用的字符串方法之一。
  • 它可以帮助我们快速统计字符串中某个字符或子串出现的个数,从而方便我们进行字符串数据分析和处理。

2、修改

(1)replace()

用于将字符串中指定的子串替换成另一个子串。它的语法如下:

str.replace(old, new[, count])
  • old 表示要被替换的子串,
  • new 表示用来替换 old 的新串,
  • count 是可选参数,表示要替换的最大次数。
    下面我们来看两个例子:
sentence = "The quick brown fox jumps over the lazy dog."
new_sentence = sentence.replace("fox", "cat")
print(new_sentence)

输出结果为:“The quick brown cat jumps over the lazy dog.”,
因为原句中的 “fox” 被替换成了 “cat”。
如果我们只想替换一次,可以传入 count 参数:

sentence = "The quick brown fox jumps over the lazy dog."
new_sentence = sentence.replace("o", "O", 1)
print(new_sentence)

输出结果为:

  • “The quick brOwn fox jumps over the lazy dog.”,因为只有第一个 “o” 被替换成了大写字母 “O”。
    需要注意的是,
  • replace() 方法返回的是新的字符串,而不会修改原字符串。
    如果原字符串中不存在要替换的子串,那么 replace() 方法将会返回原字符串本身,而不会抛出任何异常。
  • 如果要替换的子串出现在字符串中多次,可以使用 count 参数来指定最多替换几次。
  • 如果不传入 count 参数,则会将所有符合条件的子串全部替换。
    Python 字符串的 replace() 方法非常实用,可以帮助我们快速进行字符串替换操作,从而方便我们进行字符串数据处理和分析。
(2)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))       # 将集合转化为字符串,并且使用指定符号隔开

3、大小写转换

(1)capitalize()第⼀个字符转换成⼤写
var = "hello and python and hello world"
print(var.capitalize())			# 将字符串第⼀个字符转换成⼤写。
(2)title() ⾸字⺟转换成⼤写。
var = "hello and python and hello world"
print(var.title())		
(3)upper() ⼩写转⼤写。
var = "hello and python and hello world"

print(var.upper())		
(4)lower() ⼤写转⼩写
var = "hello and python and hello world"

print(var.lower())				# 将字符串中⼤写转⼩写。
(4)Istrip() 删除字符串左侧空⽩字符
var = "    hello and python and hello world      "
print(var.lstrip())		
  • rstrip()一样 删除右侧空白
  • strip():删除字符串两侧空⽩字符。
(5)just(): 填充字符串
print(var.ljust(10,"_"))	# 左对齐
print(var.rjust(10,"_"))	# 右对齐
print(var.center(10,"_"))	# 居中对齐

4、判断

(1) startswith()
  • 检查字符串是否是以指定元素开头
str.startswith(prefix[, start[, end]])

实例:

string = "Hello, World!"
if string.startswith("Hello"):
    print("Yes, the string starts with 'Hello'")
else:
    print("No, the string does not start with 'Hello'")
(2)endswith()
  • 检查字符串是否是以指定元素结尾
(3)isalpha()
  • 如果字符串所有字符都是字⺟则返回 True, 否则返回 False。
(4)isdigit()
  • 如果字符串只包含数字则返回 True 否则返回 False。
(5)isalnum()
  • 如果字符串所有字符都是字⺟或数字则返 回 True,否则返回False。
(6)isspace()
  • 如果字符串中只包含空⽩,则返回 True,否则返回 False。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值