1. 字符串的定义
- 字符串 就是 一串字符, 是编程语言中表示文本的数据类型
- 在 Python 中可以使用 一堆双引号 "" 或者 一对单引号 ' ' 定义一个字符串
- 虽然可以使用 \"" 或者 \'' 做字符串的转义, 但是在实际开发中:
- 如果字符串内部需要使用 "", 可以使用 ' ' 定义字符串
- 如果字符串内部需要使用 ' ', 可以使用 " " 定义字符串
- 可以使用 索引 获取一个字符串中 指定位置的字符 (索引计数从 0 开始)
- 也可以使用 for 循环遍历 字符串中每一个字符
大多数编程语言都是用 双引号"" 来定义字符串 !!!
string = "hello world"
for c in string:
print(c)
2. 字符串的常用操作
- 在 ipython3 中定义一个 字符串, 例如: str = " "
- 输入 xiaoming. 按下 Tap 键, ipython 会提示 字符串 能够使用的 方法
基本操作:
hello_str = "hello world"
# 1. 统计字符串长度
print(len(hello_str))
# 2. 统计某一个小字符串的次数
print(hello_str.count('l'))
# 3. 某一个子字符串第一次出现的位置
print(hello_str.index('l'))
python 内置提供的方法很多, 使得在开发时, 能够针对字符串进行更加灵活的操作! 应对更多的开发需求!
方法分类 :
1) 判断类型 - 9
2) 查找和替换 - 7
3) 大小写转换 - 5
4) 文本对齐 - 3
5) 去除空白字符 - 3
6) 拆分和链接 - 5
2.1 常用判断
# 1. 判断空白字符
space_str = " "
print(space_str.isspace())
# 2. 判断字符串中是否只包含数字
num_str = "1"
# 2.1 都不能判断小数
# num_str = "1.1"
# 2.2 unicode 字符串
# num_str = "\u00b2"
# 2.3 中文
# num_str = "一千零一"
print(num_str)
print(num_str.isdecimal())
print(num_str.isdigit())
print(num_str.isnumeric())
2.2 查找和替换
hello_str = "hello world"
# 1. 判断是否以指定字符串开始
print(hello_str.startswith("hello"))
# 2. 判断是否以指定字符串结束
print(hello_str.endswith("world"))
# 3. 查找指定字符串
# index 同样可以查找指定的字符串在大字符串在大字符串中的索引
print(hello_str.find("llo"))
# index 如果指定的字符串不存在, 会报错
# find 如果指定的字符串不存在, 会返回 -1
print(hello_str.find("adb"))
# 4. 替换字符串
# replace方法执行完成之后, 会返回一个新的字符串
# 注意: 不会修改原有字符串的内容
print(hello_str.replace("world", "python"))
print(hello_str)
2.3 文本对齐
# 要求: 居中对齐以下内容
poem = ["连峰去天不盈尺,",
"枯松倒挂倚绝壁."]
for poem_str in poem:
# 居中对齐
print("|%s|"%poem_str.center(20, " "))
poem1 = ["连峰去天不盈尺,",
"枯松倒挂倚绝壁."]
for poem_str in poem1:
# 左对齐 右对齐rjust
print("|%s|"%poem_str.ljust(20, " "))
2.4 去除空白字符
poem = ["\t\n飞流直下三千尺",
"疑是银河落九天"]
for poem_str in poem:
# 先使用strip方法去除字符串中的空白字符
# 再使用center 方法居中
print("|%s|"%poem_str.strip().center(20, " "))
2.5 拆分和连接
poem = "\t\n飞流直下三千尺\t疑\n是银河落九天"
print(poem)
# 1. 拆分字符串, split() 里面以什么分隔成列表
poem_list =poem.split()
print(poem_list)
# 2. 合并字符串
result = "".join(poem_list)
print(result)
3. 字符串的切片
- 切片 方法适用于 字符串, 列表 , 元组
- 切片 使用 索引值 来限定范围, 从一个大的 字符串 中 切出 小的 字符串
- 列表 和 元组 都是 有序 的集合, 都能够 通过索引值 获取到对应的数据
- 字典 是一个 无序 的集合, 是使用 键值对 保存数据
字符串[开始索引:结束索引:步长]
注意 :
- 指定的区间属于 左闭右开 型 [开始索引,结束索引] => 开始索引 => 范围 => 结束索引
- 从 起始 位开始, 到 结束 位的前一位 结束 ( 不包含结束位本身 )
- 从头开始, 开始索引 数字可以省略, 冒号不能省略
- 从末尾结束, 结束所以 数字可以申领, 冒号不能省略
- 步长默认为 1 , 如果连续切片, 数字和冒号都可以省略
poem = "大漠孤烟直,长河落日圆"
print(poem[2:4]) # 孤烟
print(poem[2:]) # 孤烟直,长河落日圆
print(poem[:-1]) # 大漠孤烟直,长河落日
print(poem[:]) # 大漠孤烟直,长河落日圆
print(poem[-1]) # 圆
print(poem[0::-1]) # 大
print(poem[-1::-1]) # 圆日落河长,直烟孤漠大
print(poem[::-1]) # 圆日落河长,直烟孤漠大
print(poem[::2]) # 大孤直长落圆
print(poem[::-2]) # 圆落长直孤大