字符串
好多天没有学习了,今天终于抽了点时间出来看学习视频,做点小练习,一定要每天坚持打卡!坚持打卡!
#字符串连接
print('A'+'B')
#字符串重复
print('A'*3)
#字符串切片
print('apple'[0])
print('apple'[1])
print('apple'[0:3])
print('apple'[3:])
print('apple'[:3])
#去掉空格string.strip([char])
#当char为空,默认去掉头尾空白符(包括\n,\r,\t,'',即:换行、回车、制表符、空格)
#当char不为空,函数会将char拆成一个个字符,去掉头尾指定字符
print(' A B C '.strip())
print('A BCDEFG'.strip('AFG'))
print('A BCDEFG'.strip('AFg'))
print('A BCDEFG'.strip('AGF'))
print(' A BCDEFG'.strip('A G'))
print(' A BCDEFG'.strip('AG'))
在这里不太懂回车和换行的区别呢,回车不就是换行了嘛??
print('ABCDEFG'.lstrip('AG'))
print('ABCDEFG'.rstrip('AG'))
#判断字符串是否以某个字符开始
print('ABCDE'.startswith('A'))
print('ABCDE'.startswith('AB'))
print('ABCDE'.startswith('B'))
print('\r')
print('\r')
#判断字符串是否以某个字符结束
print('ABCDE'.endswith('A'))
print('ABCDE'.endswith('DE'))
print('ABCDE'.endswith('de'))
print('ABCDE'.endswith('ED'))
print('ABCDE'.endswith('E'))
#寻找某个字符串的位置
print('ABCDEFG'.find('B'))
print('ABCDEFG'.find('a'))
#寻找某个字符串的位置
print('ABCDEFG'.index('B'))
print('ABCDEFG'.index('a'))
![运行结果](https://img-blog.csdnimg.cn/2020112422134630.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L21pemFvbGl1eWluZw==,size_16,color_FFFFFF,t_70
#字符串替换
print('today is sunday!'.replace('sunday','monday'))
print('today is sunday!'.replace('sday','monday'))
print(len('ABCD12345'))#返回字符串长度
print('ABCD1222345'.count('2'))#统计字符串中某个字符出现的字数
print('AbdD'.upper())#将字符串转化为大写
print('AbdD'.lower())#将字符串转化为小写
print('AbdD'.center(20,'-'))#字符串中间对齐,字符串长度20,不足的使用-补齐
字符串有时候在括号内有时候在括号外,这里好麻烦,有什么办法方便区分记忆什么时候字符串本身要作为参数去调用函数,什么时候字符串作为对象调用函数?
好了,结束今天的练习,明天继续!