下标
又叫索引,也叫编号
字符串
单、双、三引号都可以表示字符串
切片
截取字符串中的一部分
语法:
序列名[开始位置下标:结束位置下标:步长]
注意:下标左闭右开,步长默认为1
字符串输出
要输出name存的字符串变量的方法:
name = 'TOM'
print('我的名字是%s' % name)
print(f'我的名字是{name}')
两种方法都可以
操作方法
也就是学习操作函数
学习内容:函数名、函数功能、参数写法
常用操作:查找、修改、判断
查找
字符串查找:查找子串在字符串中的位置或者出现次数
三个函数:
find()、index()、count()
find()、index():如果某个子串存在于字符串中,返回开始位置下标(如果没找到,find返回-1,index报告异常)
count():返回子串在字符串中出现的次数,就是一个计数的函数
语法:
字符串序列.find(子串,开始位置下标,结束位置下标)
两个下标如果省略,表示在整个字符串中查找子串
rfind、rindex是从右侧开始找,但是下标还是从左边开始数(用法和结果和不加r的函数是一样的)
修改
replace():子串替换
这个函数不会修改原来的字符串,而且该函数有返回值,会返回新的字符串
字符串序列.replace(旧子串,新子串,替换次数)
mystr = 'hello world and itcast and itheima and python'
# replace() 把and换成he
mystr1 = mystr.replace('and', 'he')
print(mystr1)
split():按指定字符分割字符串
字符串序列.split(用哪个字符串分割,num)
num表示分割字符出现的次数,返回数据个数为num+1
不写num的话是全部按它分割,且会丢失分割字符
join():
子串.join(多字符串序列)
# join():合并列表里的字符串的数据为一个大字符串
mylist = ['aa', 'bb', 'cc']
new_str = '...'.join(mylist)
print(new_str)
大小写转换
mystr = 'hello world and itcast and itheima and python'
# capitalize()只把字符串中开头的首字母变成大写
new_str = mystr.capitalize()
print(new_str)
结果:Hello world and itcast and itheima and python
# title()是把每一个单词的首字母变成大写
new_str = mystr.title()
print(new_str)
结果:Hello World And Itcast And Itheima And Python
# upper() :全部字母都变成大写
new_str = mystr.upper()
print(new_str)
结果:HELLO WORLD AND ITCAST AND ITHEIMA AND PYTHON
# lower()全部字母变成小写
new_str = mystr.lower()
print(new_str)
结果:hello world and itcast and itheima and python
删除空白字符
mystr = ' hello world and itcast and itheima and python '
print(mystr)
# 删左侧的空白字符
new_Str = mystr.lstrip()
print(new_Str)
# 删右侧的空白字符
new_Str = mystr.rstrip()
print(new_Str)
# 删两侧的空白字符
new_Str = mystr.strip()
print(new_Str)
字符串对齐
字符串序列.ljust(长度,填充字符)
长度:如果原来字符有5个,长度给10,剩下的用填充字符来填充
mystr = 'hello'
mystr
'hello'
mystr.ljust(10)
'hello '
mystr.rjust(10)
' hello'
mystr.center(10)
' hello '
mystr.ljust(10, '.')
'hello.....'
判断
检查字符串以哪个子串开头或者结尾
要判断的字符串.starswith(子串,开始位置下标,结束位置下标)
2,3个参数可以省略
mystr = 'hello world and itcast and itheima and Python'
# new_str = mystr.startswith('hello')
new_str = mystr.endswith('python')
print(new_str)
次重点判断函数
mystr = 'hello world and itcast and itheima and python'
# isalpha():判断非空字符串全部由字母组成
new_str = mystr.isalpha()
print(new_str)
# isnum():判断非空字符串全部由数字组成
new_str = mystr.isdigit()
print(new_str)
mystr1 = '123456'
mystr1_new = mystr1.isdigit()
print(mystr1_new)
# isalnum():判断非空字符串全部由字母或数字或字母+数字的组合组成
print(mystr.isalnum())
mystr = 'abc123'
print(mystr.isalnum())
# isspace():判断非空字符串只有空格
mystr = ' '
print(mystr.isspace())