þ字符串处理
在日常工作中,我们经常会和字符串打交道,比如对字符串进行子串切取,反转字符串,删掉字符串中的某些子串,这一篇会讲解常用的几种字符串处理方法。 查找- >>> s = "abc">>> s.find("b")1>>> s.find("ac")-1>>> s.find("a")0>>>
ruby查找时,返回的是第一个匹配的子串的下标位置,如果没有找到,返回-1 分割字符串按照某个子串进行分割,返回分割后的列表 - >>> s = "aa12bb12cc"
- >>> s.split('12')
- ['aa', 'bb', 'cc']
大小写转换- >>> s = "abc"
- >> s.upper()
- 'ABC'
- >>> s = "ABC"
- >>> s.lower()
- 'abc'
ruby截取个人认为这是python最优雅的方法之一 - >>> s = "1234567"
- >>> s[2:5]
- '345'
- >>> s[:5]
- '12345'
- >>> s[3:]
- '4567'
- >>> s[3:-1]
- '456'
ruby追加- >>> s = "123"
- >>> t = "456"
- >>> s + t
- '123456'
ruby替换- >>> s = "1,2,3"
- >>> s.replace(",", "#")
- '1#2#3'
连接- >>> s = ['a', 'b', 'c']
- >>> ",".join(s)
- 'a,b,c'
- >>> s['xiaoli', 'xiaohong', 'siyu']>>> s.join(s)Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> s.join(s)AttributeError: 'list' object has no attribute 'join'>>> s['xiaoli', 'xiaohong', 'siyu']>>> (",").join(s)'xiaoli,xiaohong,siyu'
反转- >>> s = "abc"
- >>> s[::-1]
- >>> 'cba'
þ简易函数哈哈哈
★def 函数名(参数也可以不带):
★def print_str(s): 这里是带参数啦
输出sprint s
return s *2
print_str("shit")
★不指定的话,就输出带的默认参数
def print_default(s = "hello")
print s
print_default() #输出的是 hello
print_default("default")# 这个代餐是default
★ 不定长参数
def print_args(s, *arg):
print s
for a in arg:
print a
return
print_args("hello") #hello
print_args("hello", "world”, "1") # hello world 1
★ 参数次序可以变
def print_two(a,b):
print a, b
print_two(a ="a", b = "b")
print_two( b = "b",a ="a")
# a, b
þ实参2关键字参数:
def add(x,y):#形参þ
result = x+y
return result
代码可读性:
c = add(3,2) vs c = add(y=3, x =2)
代码可读性:def damage(skill = 1, skill2=2)
栗子:þ 默认参数的作用
def print_student_files(name, gender = ‘男’, age =18,college =‘任命小学’):
print_student_files('鸡小萌‘)’
þ朝花夕拾】函数
函数可以赋值给变量python中函数是可以赋值给变量的。 - def func_add(x, y):
- return x + y
- f = func_add
- print id(f)
- print id(func_add)
gml高阶函数一个高阶函数可以接收其他的函数作为一个参数传进来。玩过LOL的应该知道蛤蟆这个英雄。他有个技能就是吞人,然后扔出来,蛤蟆其实就是一个高阶函数,直接调用另一个英雄(英雄作为一个函数来看)。 - def func_add(x, y):
- return x + y
- def func_high(func, x, y):
- return func(x, y)
- print func_high(func_add, 1, 2)
gml匿名函数“不要问我是谁,请叫我雷锋”。匿名函数就是干这种活的,不需要显式地去def就能搞出来一个函数。 - add = lambda x,y: x + y(等于函数 赋值给add变量)
- #lambda关键字, 参数: 返回的结果
- print add(1, 2)
þ闭包官方解释:如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure)。
- def closure(x):
- def func_double():
- return x*2
- return func_double
- c = closure(1)#定义出闭包
- print c# 这里没有运行 里面这个函数 只是打印地址
- [backcolor=rgb(243, 243, 243) !important]print c()
def closure(x):
def func_double():
return x*2
return func_double
c = closure(1)
print(c)
print (c())
|