一、字符串
Python中,字符串是一种用于表示文本数据的数据类型,可以使用单引号来创建一个单行字符串,也可以用三个引号创建多行字符串。
(一)特点
- 只可以存储字符串
- 长度任意(取决于内存大小)
- 支持下标索引
- 允许重复字符串存在
- 不可以修改(增加或删除元素等)
- 支持for、while循环
二、字符串的相关常用操作
编号 | 操作 | 说明 |
1 | 字符串[下标] | 根据下表索引去除特定位置字符 |
2 | 字符串.index(字符串) | 查找给定字符的第一个匹配项的下标 |
3 | 字符串.replace(字符串1, 字符串2) | 将字符串内的全部字符串1,替换为字符串2 不会修改原字符串,而是得到一个新的字符串 |
4 | 字符串.split(字符串) | 按照给定字符串,对字符串进行分隔 不会修改原字符串,而是得到一个新的列表 |
5 | 字符串.strip() 字符串.strip(字符串) | 移除首尾的空格和换行符或指定字符串 |
6 | 字符串.count(字符串) | 统计字符串内某字符串的出现次数 |
7 | len(字符串) | 统计字符串的字符个数 |
(一)代码示例
# 空字符串的定义
def func01():
my_str01 = str()
my_str02 = ''
print(f'字符串01的内容为:{my_str01}\n字符串02的内容为:{my_str02}')
# 根据下标索引取出特定位置字符
def func02():
my_str01 = 'hello world and hello python'
# 随便取一个
print(f'{my_str01[3]}')
# 查找给定字符的第一个匹配项的下标
def func03():
my_str01 = 'hello world and hello python'
index = my_str01.index('a')
print(f'指定元素的下标为:{index}')
# 将字符串内的全部 字符串1 替换为 字符串2
def func04():
my_str01 = 'hello world and hello python'
my_str02 = my_str01.replace('hello', '你好')
print(f'字符串01的内容为:{my_str01}') # 运行发现 字符串1 的内容并未发生改变
print(f'字符串02的内容为:{my_str02},并且类型为:{type(my_str02)}') # 运行发现,会生成一个新的字符串
# 按照给定字符串,对字符串进行分隔
def func05():
my_str01 = 'hello world and hello python'
unknown = my_str01.split(' ')
print(f'新的容器内容为:{unknown},类型为:{type(unknown)}') # 运行发现是列表类型
print(f'原字符串内容为:{my_str01}') # 并且原字符串内容并没有没修改
# 移除首尾的空格和换行符或指定字符串
def func06():
# 移除首尾的空格
# You must trust yourself.————你必须相信你自己
my_str01 = ' You must trust yourself '
my_str02 = '\n\nYou must trust yourself\n\n\n'
my_str03 = '1314520You must trust yourself1314520'
my_str01 = my_str01.strip()
print(f'进行首尾空格的移除之后,字符串内容为:{my_str01}')
my_str02 = my_str02.strip()
print(f'进行首尾换行符的移除之后,字符串内容为:{my_str02}')
my_str03 = my_str03.strip('1314520')
print(f'进行指定元素的移除之后,字符串内容为:{my_str03}')
# 统计字符串内某个字符串的出现次数
def func07():
my_str01 = 'hello world and hello python'
count = my_str01.count('hello')
print(f'指定字符串在字符串内的出现次数为: {count} 次')
# 统计字符串的字符个数
def func08():
my_str01 = 'hello world and hello python'
print(f'字符串内的字符个数为: {len(my_str01)} 个')
# while循环与for循环
def func09():
my_str01 = 'hello world and hello python'
# while循环
word_for = 0
while word_for < len(my_str01):
print(f'{my_str01[word_for]} ', end="")
word_for += 1
print()
# for循环
for word_while in range(len(my_str01)):
print(f'{my_str01[word_while]} ', end="")
print()
(二)练习案例:
Ture happiness comes from belonging.————幸福源自归属感
练习案例:
将 Ture,happiness,comes,from,belonging. 中的,替换为空格
并将多余的空格以及多余的换行符与字符串进行去除
之后按照空格进行分隔,得到列表
def func10():
my_str = ' \n\nTure,happiness,comes,from,belonging. 1314520'
# 将,替换为空格
my_str = my_str.replace(',', ' ')
print(f'将,替换为空格之后的字符串的内容为:{my_str}')
# 去除多余的空格以及多余的换行符与字符串
my_str01 = my_str.strip()
my_str02 = my_str01.strip('1314520')
my_str03 = my_str02.strip()
print(f'去除了多余的空格以及多余的换行符之后的字符串内容为:{my_str03}')
# 按照空格进行分隔并生成新的列表
my_list = my_str03.split(' ')
print(f'生成的新的列表内容为:{my_list}')