导航菜单

  • 1.Python介绍
  • 2.Python解释器
  • 3.安装Python
  • 4.VSCode开发Python
  • 5.print
  • 6.进制
  • 7.编码
  • 8.Unicode2UTF8
  • 9.整数类型
  • 10.字符串类型
  • 11.布尔类型
  • 12.变量与内存
  • 13.浮点类型
  • 14.注释
  • 15.if条件
  • 16.while循环
  • 17.运算符
  • 18.输入
  • 19.列表
  • 20.元组
  • 21.集合
  • 22.字典
  • 23.for循环
  • 10.1 字符串的基本概念
  • 10.2 索引与切片
  • 10.3 常用方法
  • 10.4 字符串格式化
  • 10.5 编码
  • 10.6 项目开发要点

10.1 字符串的基本概念 #

str 表示文本,是不可变序列:修改、拼接、替换都会得到新字符串,原串不变。

s1 = "双引号"
s2 = '单引号'
s3 = """多行
文本"""

print(len(s3))           # 字符个数
print(type(s1))          # <class 'str'>

常用转义:\n 换行、\t 制表符、\" 引号。

正则、Windows 路径建议用原始字符串,反斜杠不转义

在 Python 中,字符串前面的 r 表示原始字符串(raw string)。它的作用是告诉 Python 不要将字符串中的反斜杠 \ 解释为转义字符的起始符,而是按字面原样保留。

path = r"C:\Users\data\new.txt"

10.2 索引与切片 #

text = "Hello Python"

print(text[0])       # H
print(text[-1])      # n(最后一个)
print(text[0:5])     # Hello
print(text[6:])      # Python

10.3 常用方法 #

项目里高频使用的字符串方法:

方法 用途
strip() 去掉首尾空白(表单、CSV 很常见)
lower() / upper() 大小写转换(比较、规范化)
split(sep) 按分隔符拆成列表
join(iterable) 用分隔符连接列表为字符串
replace(old, new) 替换子串
startswith() / endswith() 判断前缀/后缀(URL、文件名)
in 判断是否包含子串
email = "  User@Example.COM  "
print(email.strip().lower())              # user@example.com

csv = "apple,banana,orange"
fruits = csv.split(",")                   # ['apple', 'banana', 'orange']
print(", ".join(fruits))                  # apple, banana, orange

url = "https://api.example.com/users"
print(url.startswith("https"))            # True

filename = "report.pdf"
print(filename.endswith(".pdf"))          # True

msg = "操作成功"
print("成功" in msg)                      # True

查找与替换:

text = "Hello World"
print(text.find("World"))                 # 6,找不到返回 -1
print(text.replace("World", "Python"))    # Hello Python

10.4 字符串格式化 #

拼接变量优先用 f-string:

name = "Alice"
age = 25
print(f"用户: {name}, 年龄: {age}")
print(f"明年: {age + 1}")

10.5 编码 #

字符串在内存中是 Unicode 文本;写入文件或发网络前需 encode("utf-8") 得到 bytes。

b = "你好".encode("utf-8")
print(b.decode("utf-8"))   # 你好

10.6 项目开发要点 #

  1. 不可变:不能写 s[0] = "x";用 s = s.replace(...) 或拼接得到新串
  2. 大量拼接用 join:循环里避免 result += item,应 "".join(parts)
  3. 用户输入先 strip():避免首尾空格导致校验失败
  4. 比较邮箱、用户名:常配合 .lower() 做不区分大小写比较
  5. 解析简单 CSV/日志:split(",") 够用;复杂格式用 csv 模块
  6. 格式化只用 f-string
← 上一节 9.整数类型 下一节 11.布尔类型 →

访问验证

请输入访问令牌

Token不正确,请重新输入