从零开始学python 05——字符串

这篇博客详细介绍了Python字符串的定义、索引、切片、查找、修改和判断方法。包括使用单引号或双引号定义字符串,通过索引和切片获取字符串部分,find和index方法查找子串,replace替换子串,split和join处理字符串,以及isalpha和isdigit判断字符串内容。

一、字符串

1、字符串的定义

①一对单引号或双引号

②一对三引号

name1 = "张三"
name2 = '李四'
name3 = """王五"""
name4 = '''赵六'''
print(name1, name2, name3, name4)

 

张三 李四 王五 赵六

2、字符串的索引下标

作用:快速查找数据

①从左往右,默认从0开始  0,1,2

②从右往左,默认从-1开始  -1,-2,-3

str1 = "abcdef"
print(str1[0])
print(str1[-6])
print(str1[1])
print(str1[-5])
a
a
b
b

3、字符串的切片

切片:截取对象的一部分数据

切片语法:序列[起始下标值:结束下标值:步长]

注意点:

①切片遵循左闭右开的原则

②步长默认为1,可以省略不写,可以为负数

③下标可以是正数,也可以是负数

④起始下标值可以不写,默认从第一个位置开始切片

⑤结束下标值可以不写,默认获取到最后一个位置

序列[::-1]相当于倒序

str1 = "abcdefg"
print(str1[1:5])
print(str1[1:5:1])
print(str1[-6:-2])
print(str1[1:5:2])
print(str1[5:1:-1])
print(str1[:5])
print(str1[1::2])
print(str1[::-1])  # 倒序操作
bcde
bcde
bcde
bd
fedc
abcde
bdf
gfedcba

4、字符串的查找方法

①find:根据子串在字符串中进行查找,如果能找到返回子串的起始位置下标值,如果找不到,返回-1

rfind:从右往左找

字符串.find(子串,起始位置下标值,结束位置下标值)

②index:根据子串在字符串中进行查找,如果能找到返回子串的起始位置下标值,如果找不到,报错

rindex:从右往左找

字符串.index(子串,起始位置下标值,结束位置下标值)

str1 = "hello world and hello python"

print(str1.find("hello"))
print(str1.find("hello", 6, 25))
print(str1.find("123"))
print(str1.rfind("hello"))  # 从右往左找

print(str1.index("hello"))
print(str1.index("hello", 6, 25))
# print(str1.index("123"))  # 报错
print(str1.rindex("hello"))

 

0
16
-1
16
0
16
16

5、字符串的修改方法

①replace:字符串.replace(旧串,新串,次数)

str1 = "hello linux and hello linux"
print(str1.replace("linux", "python"))
print(str1.replace("linux", "python", 1))
hello python and hello python
hello python and hello linux

 

②split:字符串.split(分隔符,前几个分隔符分割),返回一个列表

str2 = "hello-world-python"
print(str2.split("-"))
print(str2.split("-", 1))
['hello', 'world', 'python']
['hello', 'world-python']

 

③join:拼接符.join(变量名),将变量中的元素通过拼接符拼接成字符串

list1 = ["banana", "apple", "orange"]
print("-".join(list1))
banana-apple-orange

 6、字符串的判断方法

①isalpha:判断字符串中的元素是否都是字母,返回True或False

②isdigit:判断字符串中的元素是否都是数字,返回True或False

str1 = "abcd"
print(str1.isalpha())
str2 = "123"
print(str2.isdigit())
True
True

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值