发布时间:2019-09-20 07:27:16编辑:auto阅读(2166)
1.变量 2.流程控制 3.序列、字典、集合 4.文件 |
程序中用来保存数据。定义时,不用指定变量类型,输出时使用print直接输出:
>>> say = 'hello Python'
>>> print("sunny said", say)
sunny said hello Python
#使用+连接字符串时,不带空格
>>> print("Hello" + "World")
HelloWorld数据类型:
>>> type(2**32)
<type 'int'>
>>> print(0x11)
17
>>> type(0x11)
<class 'int'>
# 瞎写的数字
>>> type(3.14159266546541651651351354313135146136269213)
<class 'float'>
>>> type(0.23j)
<class 'complex'>
>>> type(3.14 + 0.23j)
<class 'complex'>
>>> type(True)
<class 'bool'>
# 1表示真
>>> if 1:
... print(True)
...
True
>>> if 0:
... print(True)
...
>>> type("True")
<class 'str'>1.1.输入/输出
使用变量接收数据:
>>> name = input("Your name: ")
Your name: sunny
>>> print(name)
sunny
# 检查数据类型
>>> age = input('Your age:')
Your age:22
>>> type(age)
<class 'str'>
# 类型转换
>>> type(age)
<class 'str'>
>>> age = int(age)
>>> type(age)
<class 'int'>1.2.多行输出
# 多行输出
>>> info = '''
... -------- info --------
... name: %s
... age: %d
... -------- end --------
... ''' % (name, age)
>>>
>>> print(info)
-------- info --------
name: sunny
age: 21
-------- end --------
# 多行输出2
name = 'sunny'
age = '22'
info = [age, name]
info = '''
name: {0}
age: {1}
'''.format(name, age)
print(info)2.1.选择结构
>>> if income > 50000: ... donate=0.2 ... else: ... donate=0.07 ...
2.2.循环
while循环
>>> while i < 10:
... print(i)
... i=i+3
... else:
... print("Too many. How stupid it is!") file循环
import time
timeWait = 1.0
#for i in range(10):
for i in range(1,11):
time.sleep(timeWait)
print('There are %s seconds passed.' % i)序列,是有顺序的数据集合。集合中数据称为序列的元素。序列有六种:包括元组、列表、上边的字符串……。
由于元组不能改变数据,创建的元组常常不为空;而列表可以增加、修改元素,程序中经常会建立一个空表。 序列中的元素是有固定顺序的,访问时可以依据位置来找到元素,位置索引从0开始。
3.1.列表
#定义列表 >>> list2 ['china', 'smile', 8, 'india'] >>> list2[3]="print" >>> list2 ['china', 'smile', 8, 'print']
列表属于序列,序列先进先出。
| 方法 | 返回值 | 注释 |
|---|---|---|
| append(object) | None | 添加对象到列表末尾 |
| clear() | None | 删除所有元素 |
| copy() | list | 复制一份新的 |
| count(value) | int | 返回value的出现次数 |
| del object | 删除对象 | |
| extend(list) | None | 把list并入 |
| index(value[, start[, stop]]) | int | 返回找到的第一个value的索引 扩展用法,就是指定起始、结束位置…… |
| insert(pos, val) | 往某个位置插入值 | |
| len(object) | 计算列表 | |
pop([index]) | item | 去掉一个index对应的值并返回该值,默认为末尾的值 |
| remove(value) | None | 删除头一个value值 |
| reverse() | None | 反转 |
| sort() | None | 排序,默认按ASCII从小到大 |
# append() >>> LL.append([]) >>> LL ['029', '010', '025', []
# copy() >>> LL = L.copy() >>> LL ['029', '010', '025']
>>> LLL = LL.copy() >>> LLL[3][0] 'alibaba' >>> LLL[3][0] = 'Baidu' # 赋值的是一个链接地址 >>> LLL ['029', '010', '025', ['Baidu']] >>> LL ['029', '010', '025', ['Baidu']]
# pop()
>>> list2.pop()
'web'
>>> list2.remove("css")
# 替换
>>> while "asan" in list2:
... position_element = list2.index("asan")
... list2[position_element] = "print"#默认排序 >>> L.sort() #反向排序 >>> L.sort(reverse = True)
# 取值 >>> L[2] '025' # 切片 >>> L = ['029', '010', '025'] >>> L[1:2] ['010']
# 遍历列表 >>> for i in LLL: ... print(i) ... 029 010 025 ['Baidu']
3.2.元组
#元组的定义
>>> tuple=("india", "usa", "japan", 331, 402)元组属于序列,不能变更内容,元组只能进行查询操作。
| 方法 | 返回值 | 注释 |
|---|---|---|
| count(value) | 有 | 返回value的出现次数 |
| index([start [, stop]]) | 有 | 返回首个索引值 |
>>> tuple2=("hello", "css", "web", "web")
>>> tuple2.count("web")
2
>>> tuple2.index("web")
23.3.字符串
| 方法 | 返回值 | 说明 |
|---|---|---|
| capitalize() | string | 首字母大写(非首字母小写) |
| center(width[, fillchar]) | string | 打印内边距为width,填充fillchar(默认‘空格’) |
| count(sub[, start[, end]]) | int | 统计字符的个数 |
| find(sub[, start[, end]]) | int | 返回头一个子串的首个位置 |
| isalpha() | bool | 存在,全为字母,返回真 |
| isdecimal() | bool | 全为十进制,返回真 |
| isdigit() | bool | 数字,返回真 |
| isidentifier() | bool | 是合法文件名字符,返回真 |
| islower() | bool | 全小写为真 |
| isnumeric() | bool | 全为数字字符,返回真 |
| isprintable() | bool | 全为可打印字符,返回真 |
| isspace() | bool | 全空白符,返回真 |
| istitle() | bool | |
| isupper() | bool | 全大写为真 |
| lower() | string | 转换小写 |
| replace(old, new[ ,n]) | string | 替换 |
| strip() | string | 去掉两边的空白符 |
| upper() | string | 转换大写 |
实例
# capitalize() >>> str = 'zhaocaiBANK.com' >>> str2 = str.capitalize() >>> print(str2) Zhaocaibank.com >>> str = 'zhaocaiBANK.com is good.' >>> str2 = str.capitalize() >>> print(str2) Zhaocaibank.com is good.
# find()
>>> s.find('U')
9# center() >>> s.center(33, '_') '______________Server_____________'
# count()
print(str.count('a'))
print(str.count('a', 0, 6))# isdecimal() 判断的是字符串 >>> s = '98798' >>> s.isdecimal() True
3.4.字典
字典没有顺序,无序访问
| 字典方法 | 返回值 | 说明 |
|---|---|---|
| get(k[, d]) | v|d | |
| pop(k[, d]) | v|d | 删除一个字典元素,键k存在返回k对应的value,否则返回d |
| values() | dict_values | 返回“所有”存在的值 |
# get() 查询
>>> dic.get('002', 'none')
'tangerhu'
# pop() 删除
>>> print(dic.pop('001', 0))
zhangxueliang
>>> print(dic.pop('001', 0))
0
# values()
>>> dic.values()
dict_values(['tangerhu', 'yangyuting'])
# 增加/修改
>>> dic['004'] = 'zhangshifei'3.4.集合
| 集合方法 | 返回值 | 说明 |
|---|---|---|
| add() | none | 给集合添加元素 |
| pop() | element | 删除集合中元素 |
# 定义一个集合
>>> s = {'洪七公', '郭靖', '欧阳锋'}
# add() 增加元素
>>> s.add('老顽童')
# pop() 删除元素
>>> s
{'老顽童', '郭靖', '洪七公', '欧阳锋'}
>>> s.pop()
'老顽童'
>>> s.pop()
'郭靖'
>>> s
{'洪七公', '欧阳锋'}# 获取集合的长度 >>> len(s) 2 # 条件判断 >>> '郭靖' in s False
class file(object)
file(name[, mode[, buffering]])
文件类:file,打开一个文件。打开模式有‘r’(default)、‘w’、‘a’,表示‘只读’(默认)、‘只写’、‘追加’。使用‘a’、‘w’模式打开文件时,如果指定的文件名不存在就新建。 往模式中添加‘+’时表示“同时允许读、写”。 给定了缓冲参数时,0表示“无缓冲”、1表示“线性缓冲”、数字表示“缓冲大小”。
打开文件的首选方法是使用内置函数open。
| 方法 | 返回值 | 说明 |
|---|---|---|
| close() | None① | 关闭文件 |
flush() | None | 清理缓存区(写模式时写入磁盘) |
| read([n]) | 字符串 | 返回n字节的字符串,read(n) 返回直到文件结尾,read() 遇到文件结束符时,返回“空字符串” |
| readable() | 布尔 | 是否可读取 |
| readline([n]) | 字符串(保留换行符) | readline()返回当前位置到行尾 readline(n)返回最大n字节的字符串 遇到文件结束符时,返回“空字符串” |
| readlines() | 列表 | 把读取的文件内容以字符串列表形式返回 |
| seek(offset[, whence]) | None | 改变当前位置 offset,偏移量是一个字节数 whence,取值为0(默认)、1、2;分别表示“文件起始位置”、“当前位置”、“文件末尾” *不是所有文件都可以使用 |
| seekable() | 布尔 | 判断是否可变换位置 支持随机访问 |
| tell() | 整型(长整型) | 当前位置 |
| truncate([n]) | None | 截断文件(需要‘写’模式) 保留截取后的文件到当前位置(默认),或者到n字节处 直接把截取的内容(开头到n字节)写入 |
| write(...) | None | 写入文件 把“字符串”写入文件 |
| writable() | 布尔 | 是否可写入 |
| writelines(...) | None | 写入文件 把“字符串序列”写入文件 |
4.1.例子
打开文件
>>> f = open('text.txt')
# 创建文件,并且指定编码格式
>>> f = open('newfile.txt', 'w', encoding='utf-8')读文件:
read([int])实例
#读取了file的所有内容 >>> f.read() '1hello1\n2hello2\n3hello3' >>> f.read(3) '1he' #返回值都是字符串
readline([int])实例
#返回到行尾的字符串 >>> f.readline() '1hello1\n' >>> f.readline() '2hello2\n' #返回最大5字节 >>> f.readline(5) '3hell' >>> f.readline(5) 'o3' #遇到EOF,返回空串 >>> f.readline(5) ''
readlines([int])实例
#返回字符串列表 >>> f.readlines() ['1hello1\n', '2hello2\n', '3hello3'] # 遍历文件的每一行 >>> for line in f: print(line.strip())
切换位置
seek、tell实例
#返回文件起始位置 >>> f.seek(0) >>> f.tell() 0L #移动两个字节 >>> f.read(2) '1h' >>> f.tell() 0L #移动到下一行 >>> f.readline() 'ello1\n' >>> f.tell() 7L >>> f.read(2) '2h' >>> f.tell() 9L
#移动到文件末尾,不会溢出 >>> f.tell() 23L >>> f.readline() '' >>> f.tell() 23L
#从文件末尾读取7个字节 >>> f.seek(0, 2) >>> f.tell() 23L >>> f.seek(-7, 2) >>> f.readline() '3hello3'
写文件
写入文件
# write
>>> f.write("1hello1\n2hello2\n3hello3")
>>> f.close()
>>> f = open('test', 'r')
>>> f.readlines()
['1hello1\n', '2hello2\n', '3hello3']# writelines
>>> f = open('test', 'w')
>>> textStr = ['1hello1', '1hello2', '3hello']
>>> f.writelines(textStr)
>>> f.close()
>>> f = open('test', 'r')
>>> f.readlines()
['1hello11hello23hello']
#写入文件的所有内容在同一行
#需要手动添加换行符
>>> f = open('test', 'w')
>>> textStr = []
>>> textStr.append("1hello1\n")
>>> textStr.append("2hello2\n")
>>> textStr.append("3hello3\n")
>>> f.writelines(textStr)
>>> f.close()文件对象的属性
#关闭状态 >>> print f.closed False #文件编码格式 >>> print f.encoding None #打开模式 >>> print f.mode a #文件名 >>> print f.name test
打开的文件使用过后,在程序中不会自动释放。这样,一个程序执行时间很长,势必会占用大量内容。因此需要,使用close()方法释放文件对象。 上下文管理器可以在一定程度上避免忘记释放资源,原因在于上下文管理器像一个对象作用域似的。有点类似方法中的局部变量一样的概念。使用方法如下:
with open("fstab", "r+") as f:
f.write("Hello python.\n")4.2.with open
打开的文件需要及时关闭,关闭时调用“close()”。为避免,忘记关闭,建议使用“with open”打开文件,这时文件会自动关闭。
with open('text.txt' ,'r') as f:
for line in f:
print(line.strip())
# 同时打开多个文件
with open('text1.txt' ,'r') as f1,
\open('text2.txt' ,'r') as f2:
for line in f:
print(line.strip())
上一篇: iSCSI存储的3种连接方式
下一篇: Python_005_求1-2+3-4+
51296
50747
41344
38156
32627
29524
28374
23246
23212
21537
1611°
2345°
1946°
1888°
2219°
1933°
2619°
4392°
4238°
3009°