Python中len( )函数和range( )函数的用法
一、len( )函数
1、函数作用
返回字符串、列表、元组、字典等数据的长度;
2、函数语法
len(str) # str参数:字符串、列表、元组、字典等
3、示例
(1)返回字符串长度
str = "Hello Everyone!"
print "The length of the string is %d " % len(str)
输出结果: The length of the string is 15
(2)返回列表长度
list = [ 'robot', 'fly', 21, 3.14 ]
print "The length of the list is %d " % len(list)
输出结果 The length of the list is 4
(3)返回元组及字典长度
tuple = ('robot', 'fly', 21, 3.14)
dictionary = {'name':'Liming', 'age':23, 'weight':160}
print "The length of the tuple is %d " % len(tuple)
print "The length of the dictionary is %d " % len(dictionary)
输出结果 The length of the tuple is 4
The length of the dictionary is 3
二、range( )函数
1、函数作用
一般用于for循环中,用于创建整数列表;
2、函数语法
range(start, stop, step) # 一般形式:start:计数开始值 stop:计数结束值 step:计数步长
range(stop) # 省略形式:省略start和step参数:默认计数开始值为0,步长为1
range(start, stop) # 省略形式:省略step参数:默认步长为1
3、示例
(1)一般形式
list = range(0, 10, 2)
print list
输出结果 [0, 2, 4, 6, 8]
(2)省略形式
list1 = range(10)
print list1
list2 = range(3, 10)
print list
输出结果 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7, 8, 9]
总结
len( )函数和range( )函数经常再for循环中搭配使用,例如通过索引遍历字符串:
name = 'Marlon'
for index in range(len(name)) :
print name[index]
输出结果 M
a
r
l
o
n