Python常见面试题(三)

9、执行Python程序时,自动生成的.pyc文件的作用是什么?

.pyc文件是由.py文件经过编译后生成的字节码文件,其加载速度相对于之前的.py文件有所提高,且实现了源码隐藏,以及一定程度上的反编译。一般是import其他py文件的时候会生成。

4.python的自省

自省是指这种能力:检查某些事物确定它是什么、它知道什么以及它会做什么。
如:type(),dir(),getattr(),hasattr(),isinstance(),callable(obj)等

 

Python里面match()和search()的区别? 

re模块中match(pattern,string[,flags]),检查string的开头是否与pattern匹配。
re模块中research(pattern,string[,flags]),在string搜索pattern的第一个匹配值。
>>>print(re.match(‘super’, ‘superstition’).span())
(0, 5)
>>>print(re.match(‘super’, ‘insuperable’))
None
>>>print(re.search(‘super’, ‘superstition’).span())
(0, 5)
>>>print(re.search(‘super’, ‘insuperable’).span())
(2, 7)  

 

如何用Python来进行查询和替换一个文本字符串? 

# 可以使用re模块中的sub()函数或者subn()函数来进行查询和替换,
# 格式:sub(replacement, string[,count=0])(replacement是被替换成的文本,string是需要被替换的文本,count是一个可选参数,指最大被替换的数量)

import re
p = re.compile('blue|white|red')
print(p.sub('colour','blue socks and red shoes'))           # colour socks and colour shoes

print(p.sub('colour','blue socks and red shoes',count=1))   # colour socks and red shoes

# subn()方法执行的效果跟sub()一样,不过它会返回一个二维数组,包括替换后的新的字符串和总共替换的数量

 

 

Python里面如何生成随机数? 

random模块

随机实数:
random.random()                             # 返回0到1之间的浮点数
random.uniform(a, b)                        # 返回指定范围内的浮点数。

随机整数:
random.randint(a, b)                        # 返回随机整数x, a <= x <= b
random.randrange(start, stop, [, step])     # 返回一个范围在(start, stop, step)之间的随机整数,不包括结束值。

 

 

 

 

Python模块练习题

如何用Python删除一个文件

os.remove('文件') 直接从系统里面删除文件,不经过回收站
os.rmdir('文件夹') 直接从系统里面删除空文件夹,不经过回收站 

 

28.制作随机验证码,不区分大小写。

#第一种
import random
def v_code():
    code = ‘‘
    for i in range(5):
        num=random.randint(0,9)
        alf=chr(random.randint(65,90))
        add=random.choice([num,alf])
        code="".join([code,str(add)])
    return code
print(v_code())

#第二种
l = []
for i in range(6):
    alpha = chr(random.randint(65, 90))  # random.randrange(65,91)
    alpha_lower = chr(random.randint(97, 122))  # random.randrange(65,91)
    num = str(random.randint(0, 9))
    ret = random.choice([alpha,num,alpha_lower])
    l.append(ret)
print(‘‘.join(l))

 参考:https://www.cnblogs.com/chenshengqun/p/9112013.html

Python模块练习题

posted @ 2019-11-09 19:24  PythonGirl  阅读(236)  评论(0)    收藏  举报