Skip to main content

介绍

# 一、字符串之查
# 1.find 字符子序列.find(str, 开始下标, 结束下标)
# 检测子串str是否包含在原字符串mystr中,如果存在则返回第一次找到的索引值;否则返回-1
mystr = 'hello world'
print(mystr.find('h'))
print(mystr.find('hello'))
print(mystr.find('l', 1, 5))

0 0 2

# 2.index查找索引,字符子序列.index(str, 开始下标, 结束下标)
# 与 find 方法一样,只不过如果str不在mystr中会报一个异常
mystr = 'hello world'
print(mystr.index('l', 0, 4))
print(mystr.index('H'))

2


ValueError Traceback (most recent call last)

Cell In[4], line 5 3 mystr = 'hello world' 4 print(mystr.index('l', 0, 4)) ----> 5 print(mystr.index('H'))

ValueError: substring not found

# 3.count查找子串在原串中出现的次数,字符串序列.count(str, 开始下标, 结束下标)
mystr = 'hello world'
print(mystr.count('o'))
print(mystr.count('or', 3))

2 1

# 二、字符串修改
# 1.replace 字符串序列.replace(旧子串, 新子串, 替换次数)
mystr = 'hello world'
print(mystr.replace('l', 'a')) # 不指定替换次数时,会替换所有

heaao worad

# 2.split 分割 mystr.split(str, 切的次数) :用 str 来切割原字符串
a = 'he,llo,wor,ld'
print(a.split(',', 1))

['he', 'llo,wor,ld']

# 3.capitalize 首字母变成大写
a = 'hello world'
print(a.capitalize())

Hello world

# 4.lower 把字符串所有大写转换为小写
a = 'HEllo'
print(a.lower())
# 5.upper 把小写变成大写

hello

# 6.title 把字符串的每个单词的首字母大写
a = 'hello python'
print(a.title())

Hello Python

# 三、判断
# 1.islower() 检测字符串是否都由小写字母来组成。(True False)
str = 'Hello world'
print(str.islower())

# 2.isupper() 检测字符串是否都由大写字母来组成

# 3.isdigit() 是否是数字
a = 'hello123'
sum = 0
for i in a:
if i.isdigit():
sum += 1
print(f'字符串{a}包含{sum}个数字')

False 字符串hello123包含3个数字

# 4.startswith() 判断字符串是否以某个字符开头 endswith() 以xx结尾
a = 'hello wow'
print(a.startswith('h'))
print(a.endswith('o'))

True False

# 三、字符串的拼接
# 1.使用 + 直接实现拼接
ming = '三'
xing = '张'
name = xing + ming
print(name)

# 2.join 方式,在原来字符串的每个字符后面插入目标字符
a = 'hello'
print('*'.join(a))

张三 hello

# 四、删
# 1.lstrip() 删除字符串左边的空白字符
a = ' hello'
print(a)
print(a.lstrip())

# 2.rstrip() 删除右边的空白字符
# strip() 删除字符串两端的空白字符

hello hello