字符串 、 列表 、元祖
s = 'hello world'
l = [123, 'hello', 'you']
tup = ('hello','world')
字符串
创建字符串
>>> s = 'hello world'
字符串方法
>>> dir(s)
[
……………………………… #省略_xxx_带线内置方法的输出
'capitalize',
'center',
'count',
'decode',
'encode',
'endswith',
'expandtabs',
'find',
'format',
'index',
'isalnum',
'isalpha',
'isdigit',
'islower',
'isspace',
'istitle',
'isupper',
'join',
'ljust',
'lower',
'lstrip',
'partition',
'replace',
'rfind',
'rindex',
'rjust',
'rpartition',
'rsplit',
'rstrip',
'split',
'splitlines',
'startswith',
'strip',
'swapcase',
'title',
'translate',
'upper',
'zfill']
在Python中 数字、字符串和元祖都是不可变的,但字符串可以通过replace方法进行替换,replace创建一个新的字符串作为结果返回
In [1]: s = 'hello'
In [2]: s[0] = k
---------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-2-fa6a06114657> in <module>()
----> 1 s[0] = k
NameError: name 'k' is not defined
In [3]: s.replace('ll','yy') #replace方法是通过创建新的字符串作为结果
Out[3]: 'heyyo'
In [4]: s #原始的字符串并没有改变--因为字符串具有不可变性
Out[4]: 'hello'
列表
创建列表
In [1]: l = [123, 'hello', 'you']
In [2]: l
Out[2]: [123, 'hello', 'you']
列表方法
In [3]: dir(l) #省略_xxx_带线内置方法的输出
Out[3]:
[
……………… ##省略_xxx_带线内置方法的输出
'append', #L.append(object) -- append object to end
'count', #L.count(value) -> 整数 -- valued的出现次数
'extend', #L.extend(iterable) -- 通过从iterable中追加元素来扩展列表,可以合并列表
'index', #L.index(值,[start, [stop]]) ->整数——返回第一个值索引
'insert', #L.insert(index, object) --在index之前插入object
'pop', #L.pop([index]) -> item --删除并返回索引项(默认最后)
'remove', #L.remove(value) -- 删除第一次出现的value
'reverse', #L.reverse() --翻转列表
'sort'] #L.sort(cmp=None, key=None, reverse=False)
cmp -- 可选参数, 如果指定了该参数会使用该参数的方法进行排序。
key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
reverse -- 排序规则,reverse = True 降序, reverse = False 升序(默认)。
元祖
创建元祖
In [6]: tup = ('hello','world')
元祖方法
In [7]: dir(tup) #省略_xxx_带线内置方法的输出
Out[7]:
[
'count', #T.count(value) -> 整数 -- valued的出现次数
'index'] #T.index(值,[start, [stop]]) ->整数——返回第一个值索引