python字符串(我爱你的时候,要让每个人知道。 你离开的时候,我要装作不知道。)

一、什么是字符串

 
言简意赅,不需要计算值的时候,默认就是字符串,字符串是一种表示文本的数据类型
 
双引号 [" "]
三引号 [''' ''']
 

二、字符串的格式化输出

 
%s string字符串
%d double 有符号十进制整数
%f float浮点数
 
多个案例输出
 
a='警官学院'
b='苏州大学'
c='哈佛大学'
print('我的大学不是毕业于%s,而是%s,但你的好像是%s' %(a,b,c))
............................
我的大学不是毕业于警官学院,而是苏州大学,但你的好像是哈佛大学
 

三、函数值

 
1、访问字符串中的值
字符串的每个字符都对应一个下标,下标编号是从0开始
 
2、使用切片截取字符串取值
 
a='hello,this is a super man.'
print(a.__len__()) # 打印a的长度
print(len(a)) #打印a 的长度
print(a[5]) #打印下标为5的值
print(a[5:10]) # 左闭右开 只打5 不显示6
print(a[5:10:2]) # 代表字符串中下标从5到9的字符,每两个取前一个
print(a[1:-1]) #-1为从后往前数,-1不取
print(a[::-2]) #从后往前数,从-2开始截取,之后每两个取+1的数 .a eu ish,le
 
3、字符串函数
 
1、concat() 字符串拼接
2、charAt()返回指定索引处的字符
3、indexOf()找字符在哪个位置
4、trim() 左右去空格
5、replace()替换
6、format()格式化
7、substring()截取字符串
 
4、常用函数
 
①、find函数-寻找值
 
str.find(sub[,start,[,end]])
 
a='hello,i\'m lilei'
b='hello'
c='lilei'
print(a.find(c)) #根据b的内容,参照物为a,
若在a中找到b的内容,当a中有好几个一样的内容时,只取第一个值
 
 
②、index函数-根据下标寻找值的位置
str.index(sub[,start,[,end]])
print(a.index(c,1))
按照c的标准,在a中从1开始找,返回下标
③、count函数-统计值的个数
str.count(sub[,start,[,end]])
print(a.count(',',15,1))
#返回‘ ’中在字符串中的个数,如果起始下标比结束下标大,则相当于是空串
 
④、replace函数-替换值
str.replace(old,new[,max])
print(a.replace(b, '你好',1))#根据参照物b,并且替换的词汇,
# 将a中与b中一样的词换成替换的词,后面的字数,是替换a中与b中一样的词的个数
.......你好,i'm lilei,how are u!hello
 
⑤、split函数-切割
str.split(sep=None,maxsplit=-1)
print(a.split(',',1)) #将字符串切成段,第二个参数是分割次数
.....['hello', "i'm lilei,how are u!hello"]
 
⑥、capitalize函数-第一个字母大写,其余小写
 
print(a.capitalize())
 
⑦、title函数-每个字段第一个单词大写,其余小写
 
print(a.capitalize())
 
⑧、upper/lower函数
 
upper():每个单词都大写
lower():每个单词都小写
⑨、startswitch(‘值’)函数-bool值判断是否存在值
 
print(a.startswith('hello',20)) #确定a中是否以hello开头,返回bool值# 后面的数字是开头的下标点
 
⑩、endswitch(值)函数-返回是否以值结尾
 
print(a.endswith('hello',0,6))#确定a中字段是否以hello结尾,
# 下标0开头,下标5结束
 
①ljust函数()–左对齐
 
print(b.ljust(10,','))#给b的值后补充,号,仅十位,左对齐
 
②、rjust()函数–右对齐
 
print(b.rjust(10,','))#右对齐
 
③、center()函数–使值居中
 
print(b.center(10,'-'))
 
④、lstrip()-左去空格
 
print(c.lstrip())#左去空格/去指定的值
 
⑤、rsplit()函数–右去空格
 
print(a.rsplit('hello'))#右去空格/去指定的内容-------》 ['', ",i'm lilei,how are u!", '']
 
⑥、casefold()函数–等同于lower
 
print(a.casefold())#等同于lower/全是小写-----》hello,i'm lilei,how are u!hello
 
⑦、encode()函数–转为字符编码
 
print(b.encode('GBK','strict')) #转换为GBK可识别的字符编码
print(b.encode('UTF-16', 'strict'))#转换为UTF-16可识别的字符编码
 
⑧、expandtabs()–消除tab键
 
 
print(c.expandtabs().rstrip().upper().count('I')) #消除tab键/消除空格/转大写/统计I值多少
 
⑨、format()函数
 
d={"name":"张三","age":18,"gender":"男"} #格式化输出
print('{name},{age},{gender}'.format(**d))
 
print('{1}_._{0}'.format(b,c)) # 先打印下标为1的c ,再打印下标为0的b
 
 
⑩、删除字符串
 
str.strip([chars]) ----chars:移除字符串头尾指定的字符
posted @ 2022-01-16 16:24  十一没有撤退可言!  阅读(86)  评论(0编辑  收藏  举报