字符串(str)是 Python 中最基础、最常用的数据类型之一。和列表类似,字符串既有自身的方法(通过 str.method() 调用),也经常配合 Python 内置函数 使用。

下面我为你整理一份清晰、实用的表格,涵盖:

  1. 字符串常用方法(核心操作)
  2. 常用于字符串的内置函数
  3. 重要说明与对比

✅ 一、字符串常用方法(str 对象的方法)

⚠️ 字符串是不可变对象,所有方法都不会修改原字符串,而是返回新字符串
方法功能说明示例返回结果
s.upper()转大写"hello".upper()'HELLO'
s.lower()转小写"HELLO".lower()'hello'
s.capitalize()首字母大写,其余小写"hello world".capitalize()'Hello world'
s.title()每个单词首字母大写"hello world".title()'Hello World'
s.swapcase()大小写互换"HeLLo".swapcase()'hEllO'
s.strip([chars])去除首尾空白(或指定字符)" hi ".strip()'hi'
s.lstrip([chars])去除左侧空白/字符"!!hello!!".lstrip('!')'hello!!'
s.rstrip([chars])去除右侧空白/字符同上'!!hello'
s.replace(old, new[, count])替换子串(可限制次数)"apple".replace('p', 'P', 1)'aPple'
s.split([sep[, maxsplit]])按分隔符拆分为列表"a,b,c".split(',')['a','b','c']
s.rsplit(sep, maxsplit)从右边开始拆分"a.b.c.d".rsplit('.', 1)['a.b.c', 'd']
s.join(iterable)用字符串连接可迭代对象'-'.join(['a','b'])'a-b'
s.find(sub[, start[, end]])查找子串位置(未找到返回 -1)"hello".find('e')1
s.index(sub[, start[, end]])类似 find,但未找到会报错"hello".index('x')ValueError
s.count(sub[, start[, end]])统计子串出现次数"aaa".count('a')3
s.startswith(prefix)是否以某字符串开头"file.txt".startswith('file')True
s.endswith(suffix)是否以某字符串结尾"file.txt".endswith('.txt')True
s.isalpha()是否全为字母"abc".isalpha()True
s.isdigit()是否全为数字"123".isdigit()True
s.isalnum()是否为字母或数字"abc123".isalnum()True
s.isspace()是否全为空白字符" \t\n".isspace()True
s.islower() / isupper()是否全小写/大写"ABC".isupper()True
s.zfill(width)左侧补 0 到指定宽度"42".zfill(5)'00042'
s.center(width[, fillchar])居中对齐"hi".center(6, '-')'--hi--'
s.ljust(width[, fillchar])左对齐"hi".ljust(5, '*')'hi***'
s.rjust(width[, fillchar])右对齐"hi".rjust(5, '*')'***hi'

💡 小技巧:

  • split() 默认按任意空白分割(包括空格、换行、制表符)
  • "".join(list) 是拼接字符串最高效的方式(比 + 快得多)

✅ 二、常用于字符串的 内置函数

这些函数不是字符串专属,但经常用来处理字符串。

内置函数功能说明示例说明
len(s)返回字符串长度(字符数)len("你好")2支持 Unicode
str(obj)将对象转为字符串str(123)'123'几乎万能
ord(c)返回字符的 Unicode 编码ord('A')65单字符
chr(i)返回 Unicode 编码对应的字符chr(65)'A'逆运算
repr(obj)返回“官方”字符串表示(带引号等)repr("hi")"'hi'"调试用
format(value, format_spec)格式化输出(底层)format(3.1415, '.2f')'3.14'f-string 底层基于它
input(prompt)读取用户输入(返回字符串)name = input("姓名: ")总是返回 str
sorted(s)返回排序后的字符列表sorted("bac")['a','b','c']字符串 → 列表
list(s)将字符串转为字符列表list("abc")['a','b','c']常用于逐字符处理
any(s), all(s)判断是否有/全为真值any(" ")True(空格非空)注意:空字符串为 False

📌 注意:

  • len("😊") 返回 1(一个 emoji 是一个 Unicode 字符)
  • str + str 可拼接,但 str + int 会报错,需先转换

✅ 三、格式化字符串(补充重点)

虽然不属于“方法”,但字符串格式化极其重要,现代推荐方式:

方式示例说明
f-string(推荐)f"Hello {name}, age={age}"Python 3.6+,最快最简洁
.format()"Hello {}, age={}".format(name, age)灵活,支持索引、命名
% 格式化"Hello %s, age=%d" % (name, age)旧式,不推荐新项目使用

✅ 四、常见操作速查场景

需求推荐写法
去除用户输入两端空格user_input.strip()
判断是否是数字s.isdigit()(仅正整数)
更通用:try: float(s)
拆分 CSV 行line.strip().split(',')
拼接路径(避免硬拼 /os.path.join()pathlib(非字符串方法)
安全替换多次s.replace('old', 'new')(默认全部替换)
检查文件扩展名filename.lower().endswith('.txt')

✅ 五、重要注意事项

  1. 字符串不可变

    s = "hello"
    s.upper()  # 返回 "HELLO",但 s 仍是 "hello"
  2. 编码问题
    Python 3 字符串默认是 Unicode,无需担心中文乱码(但文件读写要注意 encoding)。
  3. 性能提示

    • 频繁拼接用 "".join(list),不要用 s += ...(效率低)
    • 大量文本处理可考虑 str.translate() 或正则(re 模块)