python 基础 1.5 python数据类型(三)--元组常用方法示例

#/usr/bin/python
#coding=utf-8
#@Time :2017/10/13 15:02
#@Auther :liuzhenchuan
#@File :元组.py

#tuple() 字符串转换成元组
str1 = 'abcd efg hiop'
print type(tuple(str1))
print tuple(str1)

 >>> 

<type 'tuple'>
('a', 'b', 'c', 'd', ' ', ' ', 'e', 'f', 'g', ' ', ' ', 'h', 'i', 'o', 'p')

#注意元组的写法,单个tuple元素的时候,元素后面要加逗号
n = ('abc')
m = ('abc',)
print type(n)
print type(m)
print '###'*20

 >>>  <type 'str'>

        <type 'tuple'>

#tuple的方法 count() index()
print dir(tuple)

>>> ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

#count() 方法:统计某个元素出现的次数
t1 = ('abcd','aaa','bcde','fff','eee','123','abcd')
t2 = ('a','b','c','a','d','b','a')
print t1.count('abcd')
print t2.count('a')
print '%%%%%'*20

 >>> 2

        3

#index()方法,查找元组中某个元素的切片位置
print t1.index('aaa')
print '&&&&'*20

 >>> 1

 

 

 

 

 

原文地址:https://www.cnblogs.com/lzcys8868/p/7714474.html