python函数及字符串

今天继续函数的知识总结,还有一些关于字符串的内容。

1、递归函数:函数自己调用自己

使用递归函数条件①必须留出口(函数调用必须有退出)②自己调用自己

def print_num(num):
    print(num)
    if num==1:
        return
    print_num(num-1)
    print("----->")

print_num(4)

 

2、阶乘 

例如:5! 5的阶乘  5!=5*4*3*2*1

下面用python实现求10!

def jiecheng(num):
    if num==1:
        return 1
    ret = jiecheng(num-1)
    return num * ret

result = jiecheng(10)
print(result)   #3628800

3、斐波那契数列:前面两个数相加等于后面那个数 

def feibo(num):
    b = 1
    a=1
    while num >0:
        print(b,end=" ") # end = " " 不换行

        a,b = b,a+b

        num-=1

feibo(10)    #1 2 3 5 8 13 21 34 55 89

4、字符串 

 字符串是有序序列,可以通过下标进行访问,可以通过索引获取字符

字符串一旦定义,不可修改  注意:字符串是不可变数据类型

a = "hello"
b = a[-4]
print(b)   # e

字符串切片,格式:[起始索引:结束索引:[步长]]    注意:切片含头不含尾(结束索引-1)

s = 'hello world'
s1 = s[3:7]
print(s1)#lo w

s2 = s[0:8:1] # 默认步长为 1
print(s2)  #hello wo

s3 = s[0:8:2] # 隔两个字符 取一个
print(s3) #hlow

s4 = s[0:] #hello world  默认取到最后一个  s1 = s[0:] =[:]
print(s4)  #hello world

s5 = s[:8]
print(s5)   #hello wo  默认从 0 取到第7个

s6 = s[::2] #默认从 开始取到最后,步长 2
print(s6)  #hlowrd

s7 = s[:8:2] #从0开始取到第7个,步长为2
print(s7) #hlow
s8 = s[4::2] #指定索引 4 取到最后一个 步长为2
print(s8) #owrd

# 步长为负值的练习

s9 = s[0:8:-1]  
print(s9) # 什么都取不到

s10 = s[8:0:-1] 
print(s10)  #row olle
s11 = s[::-1] 
print(s11)  #  倒序输出dlrow olleh

#起始索引 和 结束索引为负值
s12 = s[-8:5] # 从后往前开始数,然后从前往后截取
print(s12)   #lo

s13 = s[0:-8] 
print(s13) #hel

s14 = s[-1:-8:-2]  
print(s14) #drwo

5、字符串的遍历与拼接 

 字符串的遍历:for循环

username = "Hello_Mike"
for i in username:
    print("%s"%i,end=" ")
else:
    print("执行完了。。。")

#H e l l o _ M i k e 执行完了。。。

字符串的拼接:   * 把字符串复制若干次     + 把两个字符串拼接

username = "Hello_Mike"
password = "1234"
a = username+password #Hello_Mike1234
print(username * 5)  #Hello_MikeHello_MikeHello_MikeHello_MikeHello_Mike

print(username+password)  #Hello_Mike1234

 使用多个变量名接收值,要一一对应 

s1,s2 = "zh" 
print(s1)  #z
print(s2)  #h

6、字符串函数 :find rfind index rindex count()

 find(): 查找某个字符是否在字符串 中 如果有就返回第一次出现的下标 没有返回 -1

rfind() :返回从右边第一个指定字符的索引 没有返回 -1

index():  返回下标 没有找到 就报错 rindex() 返回从右边第一个指定字符的索引 没有就报错

count() :计数功能,返回指定字符在字符串中出现的个数

字符串的拆分 partition splite splitlines

split :以指定的字符切割将 字符串 分割成若个字符串 返回 列表

maxsplite: 指定最大切割次数

partition:  指定某个字符, 将整个字符串以字符为准 分割成3部分

splitlines: 按照行分割 参数是True保留换行符 False不保留

字符串的替换 replace translate

replace: 指定字符 更换新的字符 第一个参数 被替换的字符 第二个被换成字符 第三 最大替换个数

translate: 按照对应关系来进行替换内容

s6 = "hello world"
a = "world!"
b = "python"
str_tab = str.maketrans(a,b)
print(s6.translate(str_tab))  #  hehhy pytho

7、字符串函数2 center lstrip rstrip rjust ljust

 

s1="hello"
print(s1.center(10,"*"))
print(s1.ljust(10,"~"))# 左对齐 右边空余部分用指定字符替代

print(s1.rjust(10,"~"))#右对齐  左边空余部分用指定字符替代

 

s1="  hello world  "
s2 = "nihao"
print(s1.strip())    #strip()默认去除两边的空格
print(s1.lstrip())    #lstrip() 去除左边的空格
print(s1.rstrip())     #rstrip()去除右边的空格

 

s1="  hello world  "
s2 = "nihao"
# format 位置参数
print("传递的数据{},第二个数据{}".format(s1,s2))  # 格式化数据到大括号{} 中
# format 关键字参数
print("我的名字叫:{name},祖籍是:{address}".format(name="阿衰",address="重庆"))

 

8、填充与格式化:< 左对齐 ^ 居中对齐 > 向右对齐 默认是填充空格

print("我叫{:*>10},今年{:@>9}岁了".format("张三丰",100))

 

9、精度与进制

 {:.3f} 表示保留3位小数 {:.2f} 保留两位小数

print("长方形的长是{:.3f}cm,宽是{:.2f},求面积".format(5/3,7/2))
#长方形的长是1.667cm,宽是3.50,求面积
print("二进制{:b}".format(10)) #二进制1010
print("八进制{:o}".format(10)) #八进制12
print("十六进制{:x}".format(10)) #十六进制a

%% 转化字符串中有百分比的数据 

name = "大米"
age = 30
height = 1.63
weight =78
print("姓名:%s,年龄:%d, 身高:%.2f ,体重:%d 公斤 ,目前的学习进度是80%%"%(name,age,height,weight))

#姓名:大米,年龄:30, 身高:1.63 ,体重:78 公斤 ,目前的学习进度是80%

10、字符串变形 :upper lower capitalize title swapcase expandtabs

\t 空格符

s1 ="One world\tone Dream"
print(s1.upper())  #upper 把所有的小写字母转大写
#ONE WORLD	ONE DREAM
print(s1.lower())    # lower 把所有的大写字母转小写
#one world	one dream
print(s1.capitalize()) #字符串首字母大写
#One world	one dream
print(s1.title()) # 单词首字母大写
#One World	One Dream
print(s1.swapcase()) # 将字符串中大写换小写,,小写换大写
#oNE WORLD	ONE dREAM
print(s1.expandtabs())  # 把\t转换成空格符
#One world       one Dream

11、字符串判断

 

sm = "pull urself together"
print(sm.isalnum()) #判断字符串是否完全由字母或者数字组成
#False
print(sm.isalpha()) #判断字符串是否全由字母组成
#False
print(sm.istitle()) # 判断字符串是否满足title格式
#False
print(sm.isdigit()) # 判断是否全由数字组成
#False
print(sm.isupper())   #判断是否全是大写字母
#False
print(sm.islower())    #判断是否全由小写字母组成
#True
print(sm.isspace())    #判断字符串是否完全由空格
#False
sm = "pull urself together"
#startwith 判断字符串是否是以某个字符开头  可以指定下标区间
# 如果不指定下标,默认 从 0 下标开始判断
print(sm.startswith("u",5,10))

# endwith 判断是否以某个字符结尾 ,可以指定区间
print(sm.endswith("e",0,len(sm)-1))

help(sm.replace)  #help()查看某个字符串内置函数

 

12、字符编码

 

CHN="中文"
# 编码
str1 = CHN.encode("gb2312")
print(str1)  #b'\xd6\xd0\xce\xc4'
str2 = CHN.encode("utf-8")
print(str2)  #b'\xe4\xb8\xad\xe6\x96\x87'
#编码和解码格式不一致
str3 = str2.decode("gbk") # 报错 UnicodeDecodeError: 'gbk' codec can't decode byte

 

 

 

 

 

 

 

 

 

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值