说明:元组用"()"标识。内部元素用逗号隔开,元组不能二次赋值,相当于只读列表

示例1:

#!/usr/bin/python

# -*- coding: UTF-8 -*-


# 创建元组

mytuple1 = ('demo1','demo2','demo3','demo4');


# 输出元组所有元素

print mytuple1;

代码截图1:

1-1.png

运行截图1:

1-2.png


示例2:

#!/usr/bin/python

# -*- coding: UTF-8 -*-


# 创建元组

mytuple1 = ('demo1','demo2','demo3','demo4');


# 输出元组的第一个元素

print mytuple1[0];

代码截图2:

2-1.png

运行截图2:

2-2.png


示例3:

#!/usr/bin/python

# -*- coding: UTF-8 -*-


# 创建元组

mytuple1 = ('demo1','demo2','demo3','demo4');


# 输出第二个至第三个的元素 

print mytuple1[1:3];

代码截图3:

3-1.png

运行截图3:

3-2.png


示例4:

#!/usr/bin/python

# -*- coding: UTF-8 -*-


# 创建元组

mytuple1 = ('demo1','demo2','demo3','demo4');


# 输出从第三个开始至列表末尾的所有元素

print mytuple1[2:];

代码截图4:

4-1.png

运行截图4:

4-2.png


示例5:

#!/usr/bin/python

# -*- coding: UTF-8 -*-


# 创建元组

mytuple1 = ('demo1','demo2','demo3','demo4');


# 输出元组两次

print mytuple1 * 2;

代码截图5:

5-1.png

运行截图5:

5-2.png


示例6:

#!/usr/bin/python

# -*- coding: UTF-8 -*-


# 创建元组

mytuple1 = ('demo1','demo2','demo3','demo4');

mytuple2 = ('demo5','demo6');


# 输出组合的元组

print mytuple1 + mytuple2;

代码截图6:

6-1.png

运行截图6:

6-2.png

QQ截图20181030100721.png