Python中len( )函数和range( )函数的用法

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
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值