python基础二——list与字符串
2015-08-20 14:17
567 查看
1.使用命令行编译python文件
打开命令行,切换盘符,切换到python安装目录。随便找个文本软件写代码,保存为py文件。使用命令 “python 文件名” 实现编译。
用命令"exit()"退出python
2.list学习
3.分割字符串
结果:
>>>
["I'm", 'a', 'student']
['Hi', ' I am the one', ' Bye', '']
['Hi', ' I am the one', ' Bye']
['', '', '', '']
>>>
4.联合字符串
join是一个字符串的方法,而不是list的方法,该字符串可以是空字符串
5.字符串的索引和切片
(1)可以用for...in...来遍历
(2)类似于list可以通过索引方式查看
(3)不同于list的是不能够通过索引来赋值
(4)可以切片
(5)可以连接字符
6.打印文件
7.修改文件
8.练习文件处理
打开命令行,切换盘符,切换到python安装目录。随便找个文本软件写代码,保存为py文件。使用命令 “python 文件名” 实现编译。
用命令"exit()"退出python
2.list学习
from random import choice print 'Choose one side to shoot:' print 'left,center,right' you=raw_input() #无论输入什么,都转化为字符串形式 print'You kicked '+you direction=['left','center','right'] com=choice(direction) #choice函数是从list中随便选出一个值 print 'Computer saved'+com if you!=com: print'Goal!' else: print 'Ooops...'
print direction[0] #访问list中的元素 direction[0]='up' #修改 direction.append(1024) #增加 del direction[0] #删除
direction=['left','center','right','up'] direction[-1] #list中的最后一个元素 direction[-3] #list中的倒数第三个元素 direction[1:3] #结果是['center','right'] direction[1:-1] #结果是['center','right']
3.分割字符串
sentence="I'm a student" list=sentence.split() print list sentence="Hi. I am the one. Bye." list=sentence.split('.') #按'.'分割 print list sentence="Hi. I am the one. Bye" list=sentence.split('.') print list print 'aaa'.split('a')
结果:
>>>
["I'm", 'a', 'student']
['Hi', ' I am the one', ' Bye', '']
['Hi', ' I am the one', ' Bye']
['', '', '', '']
>>>
4.联合字符串
join是一个字符串的方法,而不是list的方法,该字符串可以是空字符串
>>> ''.join(['hello','world']) 'helloworld'
>>> s=";" >>> fruits=s.join(['apple','orange']) >>> print fruits apple;orange
5.字符串的索引和切片
(1)可以用for...in...来遍历
(2)类似于list可以通过索引方式查看
(3)不同于list的是不能够通过索引来赋值
(4)可以切片
(5)可以连接字符
>>> for c in word: print c, h e l l o w o r d >>> word[0] 'h' >>> word[0]='g' Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> word[0]='g' TypeError: 'str' object does not support item assignment >>> print word[5:7] wo >>> word[:] 'helloword' >>> ','.join(word) 'h,e,l,l,o,w,o,r,d' >>>
6.打印文件
>>> dirname='C:\Users\dell\Desktop' >>> f=file(dirname+'\新建文本文档.txt') #打开文件 >>> data=f.read() #阅读文件内容到data中 >>> data1=f.readline() #打印一行内容到data1中 >>> data2=f.readlines() #打印内容到list中 >>> print data #打印内容 >>> f.close()
7.修改文件
>>> f=file(dirname+'\新建文本文档.txt','w') #注意会清空原有文件
8.练习文件处理
相关文章推荐
- Python 中的进程、线程、协程、同步、异步、回调
- 在 Python 中使用 GDB 来调试 转载
- 开第一贴,记录自己学习python的过程!
- [完美解决]Python:'ascii’ codec can’t encode characters in position
- python-var
- python 获取exception 名字
- 【Python】[面向对象高级编程] 使用__slots__,使用@property
- python numpy在保持行的整体性的情况下按列排序
- python3 writerow CSV文件多一个空行
- Python:Bubble 排序算法
- Python 中的for-else用法
- Python 向 DataFrame 添加一列,该列为同一值
- Python 3 - 基本类属性和方法
- Python的字符串操作和Unicode
- Python:SELECT 排序算法
- Python模块引用问题
- python,PIL给图片加水印
- 编写Python脚本抓取网络小说来制作自己的阅读器
- python保存图片
- python 并发任务