python中字符串 方法(1)

本文深入讲解了Python中字符串的各种操作方法,包括查找子字符串、替换、分割、判断开头和结尾、大小写转换、去除空白字符等功能,以及如何使用islower、isdigit、capitalize和count等方法进行更复杂的字符串处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

find() 方法检测字符串中是否包含子字符串 str,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值``,否则返回-1。
str.find(str, beg=0, end=len(string))
str – 指定检索的字符串
beg – 开始索引,默认为0。
end – 结束索引,默认为字符串的长度。

print("abcd".find("cd"))

输出2
replace方法
str.replace(old, new[, max])
old – 将被替换的子字符串。
new – 新字符串,用于替换old子字符串。
max – 可选字符串, 替换不超过 max 次

print("this is book".replace('book','apple'))

输出 this is apple
split()方法通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串
str.split(str="", num=string.count(str)).
str – 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
num – 分割次数。默认为 -1, 即分隔所有。
返回分割后的字符串列表

str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( );       # 以空格为分隔符,包含 \n
print str.split(' ', 1 ); # 以空格为分隔符,分隔成两个

输出

['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']

```python
print("a,b,c,d".split(","))

输出['a', 'b', 'c', 'd']
str.startswith()
str.endswith()
str.lower()
str.upper()
str.strip()
str.strip()

print("this is a book".startswith("this")) #startwith 检查开头
print("this is a book".endswith("apple")) #endswith 检查结束
print("this IS a book".lower())#大写成小写
print("this IS a book".upper())#小写成大写
print("this is a book\n".strip())#默认空格换行符

输出`
True

False

this is a book

THIS IS A BOOK

this is a book

1
islower()方法检测字符串是否由小写字母组****成
islower()方法语法:
str.islower()返回true或false
isdigit() 方法检测字符串是否只由数字组成
isdigit()方法语法:
str.isdigit()返回true或false
capitalize()将字符串的第一个字母变成大写,其他字母变小写
语法:
str.capitalize()
该方法返回一个首字母大写的字符串。
count()
方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置
语法:
str.count(sub, start= 0,end=len(string))
返回字符出现的次数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值