目录
1 概述
1.1 元组
1.2 字符串
2 元组
2.1 空元组
2.2 一个值的元组
2.3 元组操作
3 字符串
3.1 字符串简介
3.2 find
3.3 split
3.4 join
3.5 strip
3.6 replace
3.7 translate
3.8 lower/upper
1 概述
在前面我们已经分享了Python思维导图,这一节,我们讲解Python基本数据类型:元组与字符串。
1.1 元组
1.2 字符串
2 元组
在 Python 中,元组是一种不可变序列,它使用圆括号来表示:
1. >>> a = ( 1 , 2 , 3 ) # a 是一个元组
2. >>> a
3. ( 1 , 2 , 3 )
4. >>> a [ 0 ] = 6 # 元组是不可变的,不能对它进行赋值操作
5. Traceback ( most recent call last ):
6. File "<stdin>" , line 1 , in < module >
7. TypeError : 'tuple' object does not support item assignment
2.1 空元组
创建一个空元组可以用没有包含内容的圆括号来表示:
1. >>> a = ()
2. >>> a
3. ()
2.2 一个值的元组
创建一个值的元组需要在值后面再加一个逗号, 这个比较特殊,需要牢牢记住 :
1. >>> a = ( 12 ,) # 在值后面再加一个逗号
2. >>> a
3. ( 12 ,)
4. >>> type ( a )
5. < type 'tuple' >
6. >>>
7. >>> b = ( 12 ) # 只是使用括号括起来,而没有加逗号,不是元组,本质上是 b = 12
8. >>> b
9. 12
10. >>> type ( b )
11. < type 'int' >
2.3 元组操作
元组也是一种序列,因此也可以对它进行索引、分片等。由于它是不可变的,因此就没有类似列表的append, extend, sort 等方法。
3 字符串
3.1 字符串简介
字符串也是一种序列,因此,通用的序列操作,比如索引,分片,加法,乘法等对它同样适用。比如:
1. >>> s = 'hello, '
2. >>> s [ 0 ] # 索引
3. 'h'
4. >>> s [ 1 : 3 ] # 分片
5. 'el'
6. >>> s + 'world' # 加法
7. 'hello, world'
8. >>> s * 2 # 乘法
9. 'hello, hello, '
但需要注意的是,字符串和元组一样,也是不可变的,所以你不能对它进行赋值等操作:
1. >>> s = 'hello'
2. >>> s [ 1 ] = 'ab' # 不能对它进行赋值
3. Traceback ( most recent call last ):
4. File "<stdin>" , line 1 , in < module >
5. TypeError : 'str' object does not support item assignment
除了通用的序列操作,字符串还有自己的方法,比如 join, lower, upper 等。字符串的方法特别多,这里只介绍一些常用的方法,如下: