首页 > 代码库 > python学习笔记--内置数据结构2
python学习笔记--内置数据结构2
1、字符串--是不可变的
定义及初始化
In [577]: s = ‘hello wolrd‘ In [578]: s Out[578]: ‘hello wolrd‘ In [579]: s = "hello python" In [580]: s Out[580]: ‘hello python‘ In [581]: s = ‘‘‘hello‘‘‘ In [582]: s Out[582]: ‘hello‘ In [583]: s = """hello""" In [584]: s Out[584]: ‘hello‘ In [585]: In [585]: s = ‘‘‘hello python ...: i like python‘‘‘ In [586]: s Out[586]: ‘hello python\ni like python‘
转义
In [587]: s = ‘i like \npython‘ In [588]: s Out[588]: ‘i like \npython‘ In [589]: print(s) i like python In [590]: s = ‘i\‘m martin‘ In [591]: s Out[591]: "i‘m martin" In [592]: path = ‘C:\\windows\nt\systemew‘ In [593]: path Out[593]: ‘C:\\windows\nt\\systemew‘ In [594]: print(path) C:\windows t\systemew In [595]: path = ‘C:\\windows\\nt\systemew‘ In [596]: print(path) C:\windows\nt\systemew In [597]: path =r‘C:\\windows\nt\systemew‘ # 加r前缀代表此字符串是自然字符串, 不会转义 In [598]: print(path) C:\\windows\nt\systemew
下标操作
In [599]: s Out[599]: "i‘m martin" In [600]: s[3] Out[600]: ‘ ‘ In [601]: s[0] Out[601]: ‘i‘ In [602]: type(s[0]) Out[602]: str In [603]: In [603]: s = ‘martin‘ In [604]: for i in s: #字符串是可迭代对象 ...: print(i) ...: m a r t i n In [605]: list(s) Out[605]: [‘m‘, ‘a‘, ‘r‘, ‘t‘, ‘i‘, ‘n‘]
字符串的操作
In [607]: lst = [‘i‘,‘am‘,‘martin‘] In [608]: lst Out[608]: [‘i‘, ‘am‘, ‘martin‘] In [609]: ‘ ‘.join(lst) Out[609]: ‘i am martin‘ In [610]: In [610]: s = ‘i love python‘ In [611]: s.split() Out[611]: [‘i‘, ‘love‘, ‘python‘] In [612]: ‘ love python‘.split() Out[612]: [‘love‘, ‘python‘] In [613]: ‘ love python‘.split(‘ ‘) Out[613]: [‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘love‘, ‘python‘] In [614]: s.split(maxsplit=1) Out[614]: [‘i‘, ‘love python‘] In [615]: s = ‘‘‘i am martin ...: i love python‘‘‘ In [616]: s.splitlines() Out[616]: [‘i am martin‘, ‘i love python‘] In [617]: ‘i am martin‘.partition(‘ ‘) Out[617]: (‘i‘, ‘ ‘, ‘am martin‘) In [618]: cfg = ‘env = PATH=/usr/bin;$PATH‘ In [619]: cfg.partition(‘=‘) Out[619]: (‘env ‘, ‘=‘, ‘ PATH=/usr/bin;$PATH‘) In [620]: s = ‘test‘ In [621]: s.upper() Out[621]: ‘TEST‘ In [622]: s.upper().lower() Out[622]: ‘test‘ In [623]: s.title() Out[623]: ‘Test‘ In [624]: s.center(30) Out[624]: ‘ test ‘ In [625]: s = ‘hahahah hehe‘ In [626]: s.strip() Out[626]: ‘hahahah hehe‘
列表, 元组, 字符串, bytes, bytearray
都是顺序存储, 顺序访问的, 都是可迭代对象, 都可以通过索引访问
In [629]: list(enumerate([1,2,3])) Out[629]: [(0, 1), (1, 2), (2, 3)] In [630]: lst = list(range(10)) In [631]: lst Out[631]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] In [632]: lst[3] Out[632]: 3 In [633]: lst[3:7] Out[633]: [3, 4, 5, 6] In [634]: lst[3:7:2] Out[634]: [3, 5] In [635]: lst[3:] Out[635]: [3, 4, 5, 6, 7, 8, 9] In [636]: lst[:7] Out[636]: [0, 1, 2, 3, 4, 5, 6] In [637]: lst[:] Out[637]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] In [638]: lst[8:5:-1] Out[638]: [8, 7, 6]
本文出自 “厚德载物” 博客,谢绝转载!
python学习笔记--内置数据结构2
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。