1. 字符串的定义
- 字符串 就是 一串字符, 是编程语言中表示文本的数据类型
- 在 Python 中可以使用 一堆双引号 "" 或者 一对单引号 ' ' 定义一个字符串
- 在 ipython3 中定义一个 字符串, 例如: str = " "
- 虽然可以使用 \"" 或者 \'' 做字符串的转义, 但是在实际开发中:
如果字符串内部需要使用 "", 可以使用 ' ' 定义字符串
如果字符串内部需要使用 ' ', 可以使用 " " 定义字符串
- 可以使用 索引 获取一个字符串中 指定位置的字符 (索引计数从 0 开始)
- 也可以使用 for 循环遍历 字符串中每一个字符
string = "hello world"
for c in string:
print(c)
2.字符串统计操作:
- 求长度、计数、位置
代码:
hello_str = "hello world"
# 1. 统计字符串长度
print(len(hello_str))
# 2. 统计某一个小字符串的次数
print(hello_str.count('l'))
# 3. 某一个子字符串第一次出现的位置
print(hello_str.index('l'))
输出:
C:\Users\10428\Desktop\Py-project\venv\Scripts\python.exe C:/Users/10428/Desktop/Py-project/ky_15_字符串统计操作.py
11
3
2Process finished with exit code 0
3.字符串常用操作
3.1 判断类型
试用:
hello_str = " "
print(hello_str.isspace())
C:\Users\10428\Desktop\Py-project\venv\Scripts\python.exe C:/Users/10428/Desktop/Py-project/ky_15_字符串统计操作.py
TrueProcess finished with exit code 0
注:不要求都会,只需有印象即可,用的时候再查
3.2 查找和替换
3.3 大小写转换
3.4 文本对齐
3.5 去除空白字符
3.6 拆分和链接