Common Function Methods in Python

type conversion

function describe example
int(x [,base]) Convert x to an integer, base is optional, base, default is decimal
float(x) convert x to a float
complex(real [,imag]) create a plural complex(1, 2) -> (1 + 2j)
str(x) convert object x to string
tuple(s) convert the sequence s to a tuple
list(s) convert the sequence s to a list
set(s) Convert to mutable collection
frozenset(s) Convert to Immutable Collection
dict(d) create a dictionary
chr(x) Convert an integer to a character chr(97) -> a
word (x) converts a character to its integer value ord(‘a’) -> 97
repr(x) convert object x to expression string repr({'runoob': 'runoob.com', 'google': 'google.com'}) -> “{'google': 'google.com', 'runoob': 'runoob.com'}”
eval(str) Evaluates a valid Python expression in a string and returns an object eval( ‘3 * 7’ ) -> 21

math function

function describe
abs(x) Returns the absolute value of a number, such as abs(-10) returns 10
max(x1, x2,…) Returns the maximum value of the given parameter, which can be a sequence
min(x1, x2,…) Returns the minimum value of the given parameter, which can be a sequence
pow(x, y) The value after x**y operation
round(x [,n]) Returns the rounded value of the floating-point number x, if n is given, it represents the number of digits rounded to the decimal point
The following belong to the random module
choice(seq) Pick an element randomly from the elements of the sequence, such as random.choice(['l','u','o']), pick an element from the list
randint(start, stop) Get a random integer from a specified range, such as random.randint(1,10), which randomly generates an integer from 1-10
randrange ([start,] stop [, step]) Get a random number from a set within the specified range that is incremented by the specified cardinality, the default value of the cardinality is 1
random() Randomly generate the next real number in the range [0,1)
uniform(x, y) Randomly generate the next real number in the range [x,y]
seed([x]) Change the seed of the random number generator. If you don't understand the principle, you don't have to set the seed, Python will help you choose the seed
shuffle(lst) Randomly sort all elements of a sequence
The following belong to the math module
ceil(x) Returns the integer of the number, such as math.ceil(4.1) returns 5
exp(x) Returns e to the power of x (ex), such as math.exp(1) returns 2.718281828459045
fabs(x) Returns the absolute value of a number, such as math.fabs(-10) returns 10.0
floor(x) Returns the rounded down integer of the number, such as math.floor(4.9) returns 4
log(x) For example, math.log(math.e) returns 1.0, and math.log(100,10) returns 2.0
log10(x) Returns the logarithm of x in base 10, eg math.log10(100) returns 2.0
modf(x) Returns the integer part and the fractional part of x. The numerical signs of the two parts are the same as x, and the integer part is represented by a floating point type.
Trigonometry part
sqrt(x) Returns the square root of a number x
sin(x) Returns the sine of x radians
asin(x) Returns the arcsine of x in radians
cos(x) Returns the cosine of x in radians
acos(x) Returns the arc cosine of x in radians
tan(x) Returns the tangent of x radians
atan (x) Returns the arctangent of x in radians
atan2(y, x) Returns the arctangent of the given X and Y coordinate values
degrees(x) Convert radians to degrees, such as degrees(math.pi/2), return 90.0
radians(x) Convert degrees to radians
hypot(x, y) Returns the Euclidean norm sqrt(x*x + y*y)
Mathematical Constants Section
pi Mathematical constant pi (pi, usually expressed as π)
e Mathematical constant e, e is a natural constant (natural constant)

String correlation

function describe example
len (string) return string length
capitalize() Convert the first character of a string to uppercase
count(str, beg=0,end=len(string 返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数
startswith(str, beg=0,end=len(string)) 检查字符串是否是以 obj 开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查
endswith(suffix, beg=0, end=len(string)) 检查字符串是否以 suffix 结束,如果beg 或者 end 指定则检查指定的范围内是否以 suffix 结束,如果是,返回 True,否则返回 False
find(str, beg=0 end=len(string)) 检测 str 是否包含在字符串中,如果指定范围 beg 和 end ,则检查是否包含在指定范围内,如果包含返回开始的索引值,否则返回-1
isalnum() 如果字符串至少有一个字符并且所有字符都是字母或数字则返 回 True,否则返回 False
isalpha() 如果字符串至少有一个字符并且所有字符都是字母则返回 True, 否则返回 False,是否纯字母
isdigit() 如果字符串只包含数字则返回 True 否则返回 False,是否纯数字
islower() 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False
isupper() 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False
isspace() 如果字符串中只包含空白,则返回 True,否则返回 False
join(seq) 以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串 s = “-“;seq = (“l”, “u”, “o”);print (s.join(seq)) -> l-u-o
lower() 转换字符串中所有大写字符为小写
upper() 转换字符串中的小写字母为大写
strip([chars]) 删除字符串左右两边的空格或指定字符
lstrip() 删除字符串左边的空格或指定字符
rstrip() 删除字符串右边的空格或指定字符
replace(old, new [, max]) 把 将字符串中的 str1 替换成 str2,如果 max 指定,则替换不超过 max 次
split(str, num=string.count(str)) num=string.count(str)) 以 str 为分隔符截取字符串,如果 num 有指定值,则仅截取 num 个子字符串 str = “this is string example….wow!!!”;print (str.split()) -> [‘this’, ‘is’, ‘string’, ‘example….wow!!!’]

list相关

函数 描述
len(list) 列表元素个数
max(list) 返回列表元素最大值
min(list) 返回列表元素最小值
list(seq) 将元组转换为列表
list.append(obj) 在列表末尾添加新的对象
list.count(obj) 统计某个元素在列表中出现的次数
list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表),类似 + 运算
list.index(obj) 从列表中找出某个值第一个匹配项的索引位置
list.insert(index, obj) 将对象插入列表
list.pop(index) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
list.remove(obj) 移除列表中某个值的第一个匹配项
list.reverse() 反向列表中元素
list.sort([func]) 对原列表进行排序
list.clear() 清空列表
list.copy() 复制列表

tuple相关

函数 描述
len(tuple) 计算元组元素个数
max(tuple) 返回元组中元素最大值
min(tuple) 返回元组中元素最小值
tuple(seq) 将列表转换为元组

字典

函数 描述
len(dict) 计算字典元素个数,即键的总数
str(dict) 输出字典,以可打印的字符串表示
dict.fromkeys() 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
dict.setdefault(key, default=None) 和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default,类似dict[key]=obj
dict.get(key, default=None) 返回指定键的值,如果值不在字典中返回default值,dict[key]
key in dict 如果键在字典dict里返回true,否则返回false
dict.values() 以列表返回字典中的所有值
dict.keys() 以列表返回一个字典所有的键
dict.items() 以列表返回可遍历的(键, 值) 元组数组
dict.update(dict2) 把字典dict2的键/值对更新到dict里,相同key的会覆盖更新
dict.clear() 删除字典内所有元素
dict.copy() 返回一个字典的浅复制
pop(key[,default]) 删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值
popitem() 随机返回并删除字典中的一对键和值(一般删除末尾对)

内置函数

函数 描述 例子
abs() 返回数字的绝对值
min() 返回给定参数的最小值,参数可以为序列
max() 返回给定参数的最大值,参数可以为序列
help() 函数用于查看函数或模块用途的详细说明 help(‘str’) # 查看 str 数据类型的帮助
setattr() 用于设置属性值,该属性必须存在 setattr(person, ‘sex’, ‘M’) # 设置属性 bar 值
getattr() 用于返回一个对象属性值
delattr() 用于删除属性,delattr(x, ‘foobar’) 相等于 del x.foobar
dir() 不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法dir(),该方法将被调用。如果参数不包含dir(),该方法将最大限度地收集参数信息
iter() 用来生成迭代器
next() 返回迭代器的下一个项目
divmod() 函数把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b) divmod(7, 2) -> (3, 1)
id() 用于获取对象的内存地址
sorted() 对所有可迭代的对象进行排序操作,sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作
enumerate() 用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中
open() 用于打开一个文件 open(‘test.txt’)
isinstance() 判断一个对象是否是一个已知的类型,类似 type(),isinstance() 会认为子类是一种父类类型,考虑继承关系
type() 判断一个对象类型,不会认为子类是一种父类类型,不考虑继承关系
sum() 对系列进行求和计算 sum([0,1,2]),sum([0,1,2,3,4], 2)
filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表,filter(function, iterable) def is_sqr(x): return math.sqrt(x) % 1 == 0 ;newlist = filter(is_sqr, range(1, 101))
issubclass() 判断参数 class 是否是类型参数 classinfo 的子类,issubclass(class, classinfo) issubclass(B,A),B是否为A的子类
pow(x, y[, z]) xy(x的y次方)的值,如果z在存在,则再对结果进行取模,其结果等效于pow(x,y) %z,pow() 通过内置的方法直接调用,内置方法会把参数作为整型,而 math 模块的pow()则会把参数转换为 float
super() 用于调用父类(超类)的一个方法
format() 输出格式化函数,具体使用方法参考:菜鸟教程http://www.runoob.com/python/att-string-format.html
len() 返回对象(字符、列表、元组等)长度或项目个数
range() range(start, stop[, step])函数返回的是一个可迭代对象(类型是对象),而不是列表类型, 所以打印的时候不会打印列表 range(5)
zip() 将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。 打包:zipped = zip(a,b),解压:zip(*zipped)
map() 根据提供的函数对指定序列做映射,map(function, iterable, …),第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表
round() 返回浮点数x的四舍五入值
hash() 用于获取取一个对象(字符串或者数值等)的哈希值 hash(‘test’)
set() 创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等

声明

以上内容来自 菜鸟教程

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325698225&siteId=291194637