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))
返回字符出现的次数