字符串: s='不迟到' s1="不早退" s2=''' <html> <head></head> <body> </body> </html> ''' print(s1) 小知识: java 中基本数据类型:4类8种! 在python中只要不是变量传递方式,带有字符串运算的都是新内存. python是解释执行。没有内存优化,编译优化。 字符串常量:即不变的量 新内存:开辟新空间 2.可以使用中括号和下标来获取单个字符,或截取字符串:即为 切片 s='不迟到,多岁的康师傅,恢复伤口,双方都恐怕,哈哈哈h' print(s[s.__len__()-1]) print(s[-2]) 如果给2个参数:4-8: print(s[4:8])#注意默认最后一位不显示; print(s[-9:-2])#注意:前面的值一定要小于后面的值 print(s[::2])#值加2 一次叠加显示即:各一个显示一个 print(s[-1::-1])#所有字倒过来显示 :即从尾部到头 print(s[::-1])#也是从尾部到头部依次全部显示 字符串用法: in:判断是否在些字符串中从在bool not in:判断是否不在此字符串中bool r/R:一样 sun='哈哈,客户\t\t收到,是\t\t东方航空,hd'
如图:若果想要显示\t该肿么办: sun=r'哈哈,客户\t\t收到,是\t\t东方航空,hd'# r的大小写都可以 print(sun)
如图:字符串格式化 s='今年' age=23 print('%s今晚 请%s 去%s 吃%s 喝%s 消费%.2f万元' %('美女','我','白宫','大餐','茅台',18)) #%.2 : 18.00 2个零 print('%s 天气不错 '%'明天') print('{}{}岁'.format(s,age,s)) print('{name} 今年 {age}'.format(name='张三',age=age)) print('{0} 今年 {1}'.format('张三',age)) print('{{{0}}} 今年 {1}'.format('张三',age)) 给张三加一个中括号即:{张三}
如图:字符串的一些函数: s='不迟到,多岁的康师傅,恢复伤口,双方都恐怕,哈哈哈h' len() 获取参数的长度 str list tuple print(s.__len__) print(len(s)) count:查找的意思 即 返回有几个值 print(s.count('静音',32)) print('hello,python red boks'.capitalize())#第一个单词的首字母大写 print('hello,python red boks'.title())#所有的单词首字母大写 列表: listA='hello,python red,boks'.split(' ') listB=[] for i in listA: temp= i.split(',') for j in temp: listB.append(j.capitalize()) print(listB)
如图: 变成字符串: listA='hello,python red,boks'.split(' ') listB=' ' for i in listA: temp= i.split(',') for j in temp: listB+=j.capitalize()+' ' print(listB)
如图:
知识扩展 str='hello,python red bo dj jo jdf my name is' print(str.split(' ',2)) print(str.rfind('python'))#find:查找字符串,返回找到的字符串下标; 即:如果没有为 -1 rfind:从右面开始 print(str.index('python3'))和find一样 replace():替换 注:但是原字符不会被改变 print(str.replace('python','java')) print(str) 小练习 输入正确的邮箱格式,并提取用户名: email='xiaobai@163.com' if email.find('@')!=-1 and email.find('.')!=-1\ and email.find('@')!=0\ and email.find('.')>email.find('@'): print('邮箱正确用户名:',email[0:email.find('@')]) else: print('格式不正确')
如图:
如果
email='xiaobai@163.com'格式不正确即:没有加‘@’
则会显示 格式不正确
如图: