1. len()方法
用法:len(obj)
说明:返回对象(字符串、列表等)的长度或元素的个数
参数:对象obj
返回值:对象的长度
示例代码:
str1 = "Hello World"
len1 = len(str1)
print("len(str)= %s" % len1)
list1 = [1, 2, 3, "a", "b", "c"]
len2 = len(list1)
print("len(list)= %s" % len2)
运行结果:
len(str)= 11
len(list)= 6
2. count()方法
用法1:count(obj)
说明:返回对象在(字符串、列表等)中出现的次数
参数:对象obj
返回值:出现的次数,未出现返回0
示例代码:
str1 = "Hello World"
count1 = str1.count("l")
print("'l'的出现次数: %d" % count1)
list1 = [1, 2, 3, "1", "2", "3"]
count2 = list1.count(2)
print("'2'的出现次数: %d" % count2)
运行结果:
'l'的出现次数: 3
'2'的出现次数: 1
用法2:count(obj, start, end)
说明:返回对象在字符串的[start, end]区间出现的次数
参数:对象obj,开始位置,结束位置
返回值:出现的次数,未出现返回0
示例代码:
str1 = "Hello World"
count1 = str1.count("l", 5, 9)
print("'l'的出现次数: %d" % count1)
运行结果:
'l'的出现次数: 0
3. index()方法
用法1:index(obj)
说明:返回对象在(字符串、列表等)中首次出现的位置
参数:对象obj
返回值:首次出现的位置,未找到返回ValueError: substring not found
示例代码:
str1 = "Hello World"
index1 = str1.index("l")
print("'l'首次出现的位置: %d" % index1)
list1 = [1, 2, 3, "1", "2", "3"]
index2 = list1.count(2)
print("'2'首次出现的位置: %d" % index2)
运行结果:
'l'首次出现的位置: 2
'2'首次出现的位置: 1
用法2:index(obj, start, end)
说明:返回对象在字符串的[start, end]区间中首次出现的位置
参数:对象obj
返回值:首次出现的位置,未找到返回ValueError: substring not found
示例代码:
str1 = "Hello World"
index1 = str1.index("l", 3, 6)
print("'l'首次出现的位置: %d" % index1)
运行结果:
'l'首次出现的位置: 3