Python语法结构(二)

系统管理模块

#shutil模块
        shutil.copyfileobj(fsrc,fdst[,length])
             将类似文件的对象fsrc的内容复制到类似文件的对象fdst  

#拷贝文件对象
		>>> import shutil
		>>> f1 = open('/bin/touch','rb')
		>>> f2 = open('/tmp/touch','wb')
		>>> shutil.copyfileobj(f1,f2)
		>>> f1.close()
		>>> f2.close()
		>>> 
		(nsd1905) [root@localhost day04]# md5sum /bin/touch /tmp/touch 
		42a30752aa6ef51fb39cd8ff59a8cfb1  /bin/touch
		42a30752aa6ef51fb39cd8ff59a8cfb1  /tmp/touch

shutil.copyfile(src,dst,*,follow_symlinks=Ture)
            将名为src的文件的内容(无元数据)复制到名为dst的文件,然后返回dst 

#拷贝文件内容				
		>>> import shutil
		>>> shutil.copyfile('/etc/motd','/tmp/motd')
		'/tmp/motd'
		(nsd1905) [root@localhost day04]# md5sum /etc/motd /tmp/motd 
		d41d8cd98f00b204e9800998ecf8427e  /etc/motd
		d41d8cd98f00b204e9800998ecf8427e  /tmp/motd

# 拷贝目录,记住
	>>> shutil.copytree('/etc/security', '/var/tmp/anquan')

# 删除目录,记住
	>>> shutil.rmtree('/var/tmp/anquan')

# 改变属主、属组,记住
	>>> shutil.chown('/etc/motd', user='bob', group='bob')
# 移动,记住
	>>> shutil.move('/tmp/motd', '/var/tmp/')					
				

### subprocess模块

    - 用于执行系统命令

>>> import subprocess
		# 在shell环境中执行ls ~
		>>> subprocess.run('ls ~', shell=True)
		>>> subprocess.run('id root', shell=True)

		# 将输出和错误保存到result中
		>>> result = subprocess.run('id root', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		>>> result.returncode   # 相当于$?
		0
		>>> result.stdout  # 查看标准输出
		b'uid=0(root) gid=0(root) \xe7\xbb\x84=0(root)\n'
		>>> result.stdout.decode()  # 将bytes转为str
		'uid=0(root) gid=0(root) 组=0(root)\n'

		>>> result = subprocess.run('id zhaoliu', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		>>> result.stderr
		b'id: zhaoliu: no such user\n'
		>>> result.returncode
		1

 ##模块布局

#!/root/www/bin/python     # 解释器位置
"""文档字符串

在help查看时,能够看到的模块说明
"""

# 模块导入
import os
import string

# 全局变量定义
all_chs = string.ascii_letters + string.digits

# 类的定义
class MyClass:
    pass

# 函数定义
def func1():
    pass

# 主程序代码
if __name__ == '__main__':
    mc = MyClass()
    func1()

 ##序列对象

>>> list('abc')   #list函数将对象转为列表
['a', 'b', 'c']

>>> tuple('abc')    #tuple函数将对象转为元组
('a', 'b', 'c')

# reversed函数用反转序列对象
>>> from random import randint
>>> nums = [randint(1, 100) for i in range(10)]
>>> nums
[1, 30, 79, 99, 39, 61, 96, 36, 48, 42]
>>> reversed(nums)
<list_reverseiterator object at 0x7f4b34134c50>
>>> for i in reversed(nums):
...   print(i)
>>> list(reversed(nums))
[42, 48, 36, 96, 61, 39, 99, 79, 30, 1]
>>> nums   # nums本身不会改变
[1, 30, 79, 99, 39, 61, 96, 36, 48, 42]


# sorted用于排序
>>> sorted(nums)  # 默认升序排列
[1, 30, 36, 39, 42, 48, 61, 79, 96, 99]
>>> sorted(nums, reverse=True)  # 降序排列
[99, 96, 79, 61, 48, 42, 39, 36, 30, 1]

# enumerate函数可以同时得到序列对象的下标和值
for ind, num in enumerate(nums):
    print(ind, num)

##字符串格式化操作符

>>> '%s is %s years old' % ('bob', 20)
		'bob is 20 years old'
>>> '%s is %d years old' % ('bob', 20)
		'bob is 20 years old'
>>> '5 / 3 = %d' % (5 / 3)  # %d: 10进制整数
		'5 / 3 = 1'
>>> '5 / 3 = %f' % (5 / 3)  # %f: 浮点数
		'5 / 3 = 1.666667'
>>> '5 / 3 = %5.2f' % (5 / 3)  # %5.2f:共5列,小数点2位,空格也站位
		'5 / 3 =  1.67'

>>> '%8s%5s' % ('name', 'age')  # %8s: 占8列,右对齐
		'    name  age'
>>> '%8s%5s' % ('bob', 20)
		'     bob   20'
>>> '%-8s%-5s' % ('name', 'age')  # 负数表示左对齐
		'name    age  '
>>> '%-8s%-5s' % ('bob', 20)
		'bob     20   '	
				

### 字符串方法

>>> s1 = '1234'  #先赋值变量,如果写字符串按tab没有提示
>>> s2 = '12a34'

>>> s1.            #输入变量,按两下tab
s1.capitalize(    s1.isalnum(       s1.join(          s1.rsplit(
s1.casefold(      s1.isalpha(       s1.ljust(         s1.rstrip(
s1.center(        s1.isdecimal(     s1.lower(         s1.split(
s1.count(         s1.isdigit(       s1.lstrip(        s1.splitlines(
s1.encode(        s1.isidentifier(  s1.maketrans(     s1.startswith(
s1.endswith(      s1.islower(       s1.partition(     s1.strip(            #删除空白字符
s1.expandtabs(    s1.isnumeric(     s1.replace(       s1.swapcase(
s1.find(          s1.isprintable(   s1.rfind(         s1.title(
s1.format(        s1.isspace(       s1.rindex(        s1.translate(
s1.format_map(    s1.istitle(       s1.rjust(         s1.upper(            #小写转大写
s1.index(         s1.isupper(       s1.rpartition(    s1.zfill(
>>> s1.

 字符串练习

# 字符串方法
>>> s1.center(30)  # 居中
'             1234             '
>>> s1.center(30, '*')   # 居中,两边用*号填充
'*************1234*************'
>>> s1.ljust(30, '#')  # 左对齐
'1234##########################'
>>> s1.rjust(30, '@')  # 右对齐
'@@@@@@@@@@@@@@@@@@@@@@@@@@1234'
>>> '  \thello world.\n'.strip()  # 移除两端空白字符
'hello world.'
>>> '  \thello world.\n'.lstrip()  # 移除左端空白字符
'hello world.\n'
>>> '  \thello world.\n'.rstrip()  # 移除右端空白字符
'  \thello world.'
>>> s3 = 'abc'
>>> s3.upper()  # 转成大写
'ABC'
>>> 'HELLO WORLD'.lower()  # 转成小写
'hello world'

>>> s1
'1234'
>>> s1.islower()  # 有字母,并且是小写为True
False
>>> s2
'12a34'
>>> s2.islower()  # 有字母,并且是小写为True
True
>>> 'HAO123'.isupper()  # 字母是大写的
True
>>> s1.isdigit()  # 所有字符全部为数字
True
>>> s2.isdigit()
False
>>> 'Hao'.isalpha()  # 字符全为字母
True
>>> 'Hao123'.isalpha()
False
>>> 'Hao123'.isalnum()  # 字符全部为字母或数字
True
>>> 'Hao123'.startswith('Hao')  # 字符串以Hao开头吗?
True
>>> 'Hao123'.endswith('ab')  # 字符串以ab结尾吗?
False
>>> 'hao 123 abc'.split()   # 切分字符串
['hao', '123', 'abc']
>>> 'hao-123-abc'.split()
['hao-123-abc']
>>> 'hao-123-abc'.split('-')  # 以-为分隔符,切分字符串
['hao', '123', 'abc']
>>> s1.replace('12', 'abcd')  # 替换
'abcd34'

 

## 列表

- 列表属于容器、可变、序列

>>> alist = [13,2,356,23]
>>> alist[-1] = 100            #修改列表
>>> alist
[13, 2, 356, 100]
>>> alist[1:3]
[2, 356]
>>> alist[1:3] = [ 10,20,30]        #按下标修改,可修改多个
>>> alist
[13, 10, 20, 30, 100]
>>> alist.                    ##列表方法
alist.append(   alist.count(    alist.insert(   alist.reverse(
alist.clear(    alist.extend(   alist.pop(      alist.sort(
alist.copy(     alist.index(    alist.remove(   
>>> alist.

列表方法

方法描述
append()追加,在列表的末尾添加一个元素
clear ()删除列表中的所有元素
copy ()复制列表,将列表中的值赋值给另一个变量
count ()返回具有指定值得元素数量
extent ()将列表元素(或任何可迭代的元素)添加到当前列表的末尾
index ()返回具有指定值得第一个元素的索引
insert ()在指定位置添加元素
pop ()删除指定位置的元素
remove ()颠倒列表的顺序
sort ()对列表进行排序

 

 

 

 

 

 

 

 

 

 

 

按顺序应用

>>> alist.append(200)            #追加到列表最后
>>> alist
[13, 10, 20, 30, 100, 200]


>>> alist.clear()    #清除
>>> alist
[]


>>> a = alist.copy()   ##返回列表副本
>>> a
[13, 2, 356, 23]
>>> alist
[13, 2, 356, 23]

>>> alist[1:3]= [2,2,2,2]  #添加多个重复元素
>>> alist
[13, 2, 2, 2, 2, 23]
>>> s=alist.count(2)        #统计指定值出现次数
>>> s
4

>>> a = (1,2,3,4,5)
>>> alist = ['a','b','c']
>>> alist
['a', 'b', 'c']
>>> alist.extend(a)      #将元组添加到alist列表,在末尾添加
>>> alist
['a', 'b', 'c', 1, 2, 3, 4, 5]

>>> a  = ['s','d','e']     
>>> alist.extend(a)      #同为列表也可以追加 
>>> alist
['a', 'b', 'c', 1, 2, 3, 4, 5, 's', 'd', 'e']


>>> alist
['a', 'b', 'c', 1, 2, 3, 4, 5, 's', 'd', 'e'] 
>>> a = alist.index(1)    #返回指定值首次出现的位置
>>> a
3


>>> alist= ['sougou','Google','taobao'] 
>>> alist.in
>>> alist.insert(1,'baidu')      #在指定位置拆入元素
>>> alist
['sougou', 'baidu', 'Google', 'taobao']


>>> alist
['sougou', 'baidu', 'Google', 'taobao']
>>> a = alist.pop(1)            #  删除指定位置的元素
>>> alist
['sougou', 'Google', 'taobao']


>>> alist.remove('taobao')        #删除列表中的某个元素
>>> alist
['sougou', 'Google']


>>> alist = [0 + i for i in range(1,11)]   #列表解析
>>> alist
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]   
>>> alist.reverse()                    #倒序排序
>>> alist
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]


>>> alist.sort()                    #排序
>>> alist
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

基础知识借鉴网址

https://www.w3school.com.cn/python/python_ref_list.asp

https://www.runoob.com/python3/python3-list.html 

#元组

元组是容器, 不可变,顺序

元组相当于是静态的列表

>>> atu=(10,35,45,1,5)
>>> atu.
atu.count(  atu.index(  
>>> atu.count(1)            #统计出现次数
1
>>> atu.index(1)            #返回数值1的下标
3

 

## 字典

- 字典属于容器、可变、映射类型
- 字典的key不能重复,value可重复
- 字典的key必须是不可变对象

>>> adic = dict(['ab',['name','bob'],('age',20)])
>>> adic
{'a': 'b', 'name': 'bob', 'age': 20}

>>> sdic = {}.fromkeys(['bob','lili','zs','dc'],20)
>>> sdic
{'bob': 20, 'lili': 20, 'zs': 20, 'dc': 20}
>>> 

字典遍历方法

>>> adic
{'a': 'b', 'name': 'bob', 'age': 20}
>>> for key in adic:
...     print(key,adic[key])
... 
a b
name bob
age 20
>>> '%s is %s year old' %(adic['name'],adic['age'])
'bob is 20 year old'
>>> '%(name)s is %(age)s years old' % adic
'bob is 20 years old'

更新字典

# 更新字典。字典中有key为修改,没有为添加
>>> adict['email'] = 'bob@tedu.cn'
>>> adict['age'] = 22

# 判断字典有没有某个key
>>> 'email' in adict
True
>>> 22 in adict
False

### 字典的方法

方法描述
get ()取出value。key不存在,默认返回None,value不存在,返回指定值
keys()返回所有的key,可以使用 list() 来转换为列表
values()返回所有的value,可以使用 list() 来转换为列表
items()返回(key, val)组成的列表
pop('a')弹出key为a的项目
popitem()弹出某个项目
update()合并字典

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值