本文记录Python3中的一些常用的库函数
input
:input
函数用于输入,它返回的值是str类型。在input
中加上字符串可以作为提示语句来显示在屏幕上:
>>> name = input('please enter your name: ')
please enter your name: chenf99
>>> print('hello,', name)
hello, chenf99
range
:range
函数可用于产生一个整数序列,再通过list
函数可以转换为list:
>>> list(range(5))
[0, 1, 2, 3, 4]
- 各种用于转换类型的函数:
int()
、float()
、str()
、bool()
、hex()
等
>>> int('123')
123
>>> int(12.34)
12
>>> float('12.34')
12.34
>>> str(1.23)
'1.23'
>>> str(100)
'100'
>>> bool(1)
True
>>> bool('')
False
>>> hex(1024)
'0x400'
find
和rfind
函数检测在字符串的指定范围内是否包含某个子串,如果包含则返回子串开始的索引值,不包含则返回-1。它们的区别是find
为从左向右找,rfind
为从右向左找
str.find(str, beg=0, end=len(string))
str.rfind(str, beg=0 end=len(string))
strip()、lstrip()、rstrip()
分别除去两端、左端、右端指定的字符,默认为去除空白字符
str = "123abcrunoob321"
print (str.strip( '12' ))
3abcrunoob3
split
函数通过指定的分隔符对字符串进行切片,并且可以指定分割次数,分割结果是字符串列表。仅支持单一分隔符,且不感知空格数量
str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( );
print str.split(' ', 1 );
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
- 列表相关函数:
append、extend、insert、remove、reverse
a = [1, 2, 3]
b = [5, 6]
a.append(b)
print(a)
a.extend(b)
print(a)
a.insert(1, 'K')
print(a)
a.insert(3, 'K')
print(a)
a.remove(a[3])
print(a)
a.insert(1, 'K')
del a[3]
print(a)
a.reverse()
print(a)
print(a.index('K'))
map
函数根据提供的函数来对指定的序列进行映射,python2.x中返回值是列表,python3.x中返回值是迭代器
map(function, iterable, ...)
>>> def square(x):
... return x ** 2
...
>>> list(map(square, [1, 2, 3]))
[1, 4, 9]
>>> tuple(map(square, [1, 2, 3]))
(1, 4, 9)
>>> list(map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6]))
[5, 7, 9]
filter
函数根据提供的函数过滤掉指定序列中的一些元素,python2.7中返回列表,python3.x中返回迭代器
filter(function, iterable)
>>> def is_odd(x):
... return x % 2 != 0
...
>>> list(filter(is_odd, range(1, 10)))
[1, 3, 5, 7, 9]
>>> list(filter(lambda x: x % 2 != 0, range(1, 10)))
[1, 3, 5, 7, 9]
reduce
函数主要对列表中的元素进行累积,累积的方法是提供的函数,返回值是计算结果
reduce(function, iterable[, initializer])
function -- 函数,有两个参数
iterable -- 可迭代对象
initializer -- 可选,初始参数
使用方法:
from functools import reduce
print(reduce(lambda x, y: x ** y, [2, 3, 4]))
实现:
def myReduce(function,sequence,startValue):
for x in sequence:
startValue = function(startValue,x)
return startValue