python 面试

python判断变量的类型

import collections

if isinstance(theElement, collections.Iterable):
    # iterable
else:
    # not iterable

去除字符串作用的空格,tab

s = s.strip(' \t\n\r')

手动抛出异常

raise Exception("I know python!")

查看对象的类型

使用type,type([]),可以用isinstance函数.也对内建函数管用,用isinstance()比type()更好.

isinstance()的第二个参数也接受类型的元组,所以也可以一次检查多种类型.

python 打印重定向:stderr

import sys
 sys.stderr.write('spam\n')

 print >> sys.stderr, 'spam'

 from __future__ import print_function
 print('spam', file=sys.stderr)

将两个列表合并

mergedlist = listone + listtwo

生成包含大写字母和数字的随机字符串

我希望生成N大小的字符串.

里面只含有数字和大写字母,比如:

  • 6U1S75
  • 4Z4UKK
  • U911K4
''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))

或者创建一个方法

def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
...    return ''.join(random.choice(chars) for _ in range(size))

使用字典实现switch

def f(x):
    return {
        'a': 1,
        'b': 2,
        }.get(x, 9)    # 9 is default if x not 
        

翻转字符串

'hello world'[::-1]

if name == "main":是干嘛的?

原因是有时你需要你写的模块既可以直接的执行,还可以被当做模块导入到其他模块中去.通过检查是不是主函数,可以让你的代码只在它作为主程序运行时执行,而当其他人调用你的模块中的函数的时候不必执行.

python的is

is是对比地址,==是对比值

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容