1.字符串的下标索引
name='james'
print(name[0])
2.字符串是一种不能修改的数据容器和元组一样
name='james'
print(name)
name[0]='s'
print(name)
3.字符串的操作
1.查询指定字符的下标
name='james'
print(name)
print(f"j的序号:{name.index('j')}")
2.替换字符串
用 字符串.replace(old,new)
这个有返回值的,返回值是新的字符串
旧的字符串不会被修改
name='james'
print(name)
newname=name.replace('j','jack')
print(f"旧的字符串:{name}")
print(f"新的字符串:{newname}")
3.分割字符串
字符串.split(分隔符字符)
分割后存入到列表中
senten="hello world hello python"
split_sentence=senten.split( )
print(split_sentence)
print(type(split_sentence))
print(senten)
4.字符串的规整(移除首尾指定的字符串)
变量=字符串.strip(参数)
去除字符串两边的空格
senten=" hello world "
print(senten)
newsenten=senten.strip()
print(newsenten)
去除字符串左右两边的12
senten="12 hello world 21"
print(senten)
newsenten=senten.strip('12')
print(newsenten)
注意左右两边都要为12 为空格的话就去不掉了
senten="12 hello world 21 "
print(senten)
newsenten=senten.strip('12')
print(newsenten)
5.统计字符串某个字符出现的次数
senten="hello world "
print(senten)
num=senten.count('l')
print(num)
6.字符串的长度
包含空格
senten="hello world"
print(senten)
print(f"字符串的长度为{len(senten)}")
7.字符串的遍历
与之前一样
8.字符串全部变大写
a="abcDEF"
a=a.upper() #小写的lower
print(a)
a=a.replace()
9.寻找字符串的字符的位置
返回字符的下标,没有就返回-1
a="abcDEF"
a=a.upper() #小写的lower
b=a.find('D')
print(b)
10 .以某个字符分割字符串生成新的字符串
a="abcDEF"
b=','.join(a) # ,是分割的,a是字符串
print(b)
11.字符串的逆置
a=" a,bc,DEF"
b=(a.split(',')) # ,是分割的,a是字符串
print(b)
c=''.join(reversed(b))
print(c)
12.字符与数字的转化
a=ord('A')
print(a)
char=chr(66)
print(char)