string函数
help(replace())查看函数用法
s="hello world"
1.首字母大写
str.capitalize()
s.capitalize()
=>"Hello world"
2. 替换
str.replace()
s.replace("hello","Hello")
=>"Hello world"
str.replace("需替换的值","替换成的值",替换次数)
3. 切割
str.split()
ip="192.168.1.1"
ip.split(".")
=>['192','168','1','1']
str.split("切割的字符",切割次数)
import string
string.replace()
string.replace(字符串变量s,'需替换的字符','替换成的字符','替换次数')
序列处理函数
长度
len()
过滤
filter()
l=range(10)
def f(x):
if x>5:
return True
filter(f,l)
=>[6,7,8,9]
将序列l的值,分别传入x函数,对列表的值进行筛选
将元组进行拼合
name=['milo','zou','tom']
age=['21','31','41']
zip()
zip(name,age)
=>[('milo','21'),('zou','31'),('tom','41')]
map()
map(None,name,age,tel)
=>效果和zip相同
test=['1']
zip(name,age,test)
=>[('milo','21','1')]
当其中一个元组的长度不够时,只能遍历出1个值
map(None,name,age,tel)
=>[('milo','21','1'),('zou','31',None),('tom','41',None)]
而map中None的作用,可以在元组长度不够时,用None进行补充
map除了可以对函数进行遍历,还可以对遍历后的数据进行函数的运算
reduce()
6的阶乘:6*5*4*3*2*1
l=range(1,101)
>>> from functools import reduce
>>> reduce(rf,(1,2))
3
lambda
filter(lambda x:x%2==0,list)
lambda 参数x,参数y:公式x+y,元组