字符串是字符的容器,一个字符串可以存放任意数量的字符。字符串同样无法修改。
字符串的定义
字符串中的每个字符都为一个元素,同样可以用下标号索引,例如:
1
2
3
|
s = 'hello'
print(s[0]) #输出h
print(s[-1]) #输出o
|
此外,需要注意空格也属于一种字符
1
2
3
|
s = 'you and me'
print(s[3])
print(s[-3]) #输出空格
|
字符串的常用操作
找到特定字符串的下标
1
2
|
s = 'you and me'
print(s.index('and')) #输出4
|
字符串的替换
1
2
3
4
|
s1 = '12345666'
s2 = s1.replace('6','7') #字符串.replace(‘要替换的字符’,‘替换后的字符’)
print(s1) #输出12345666
print(s2) #输出12345777
|
可见replace并没有修改字符串本身,而是产生了一个新字符串,因此你需要一个变量来接收它
字符串的分割
1
2
3
4
|
s1 = 'you and me'
s2 = s1.split(' ') #字符串.split('分割依据')
print(s1) #输出you and me
print(s2) #输出['you', 'and', 'me']
|
在括号内填入你想要按照哪一个字符分割后,split会将原字符串分割为若干元素并装入一个列表
但是原字符串仍被未修改,因此你需要一个变量来接收分割结果
字符串的规整操作
当括号内不填参数时,strip会去除字符串前后的空格
1
2
|
s = ' you and me '
print(s.strip()) #输出you and me
|
当括号内填入参数后,strip会去除字符串首尾全部满足参数的字符(不严格:满足参数的任意字符就去除)例:
1
2
|
s = '23you and me34'
print(s.strip('234')) #输出you and me
|
此处表明于strip并不是找到'234’这一整体才去除,而是把'2’、‘3’、‘4’分别都去除
统计字符串中某字符串出现的次数
1
2
|
s = 'itheima and itcast'
print(s.count('it')) #输出2
|
严格按照所查找字符串整体查找,区分大小写
统计字符串的长度
同样包括空格,用法与之前相同
1
2
|
s = 'you and me'
print(len(s)) #输出10
|
字符串的遍历
while循环
示例:
1
2
3
4
5
6
|
s = '12345'
index = 0
while index < len(s):
a = s[index]
print(a) #对元素a进行处理
index += 1
|
for循环
示例:
1
2
3
4
|
s = '12345'
for i in range (0,len(s)):
a = s[i]
print(a)
|