1. 引言
字符串(String)是 Python 中最基础、最常用的数据类型之一,用于表示文本信息。Python 提供了丰富的内置字符串方法,可以方便地进行查找、替换、分割、格式化等操作。掌握这些方法能极大提升日常编码效率。本文将对 Python 字符串的常用方法进行系统性总结,并辅以代码示例。
2. 字符串基础与创建
在 Python 中,字符串可以使用单引号 '、双引号 " 或三引号 '''/""" 创建。
str1 = 'Hello, World!'
str2 = "Python String"
str3 = '''多行
字符串'''
str4 = """这也是
一个字符串"""
字符串是不可变(immutable)对象,任何修改操作都会返回一个新的字符串。
3. 常用方法分类总结
3.1 大小写转换
方法 描述 示例 str.lower()返回字符串的小写版本 "Hello".lower() → "hello"str.upper()返回字符串的大写版本 "Hello".upper() → "HELLO"str.capitalize()将字符串首字母大写,其余小写 "hello world".capitalize() → "Hello world"str.title()将每个单词的首字母大写 "hello world".title() → "Hello World"str.swapcase()交换字符串中的大小写 "Hello World".swapcase() → "hELLO wORLD"
s = "pYtHoN sTrInG"
print ( s. lower( ) )
print ( s. upper( ) )
print ( s. capitalize( ) )
print ( s. title( ) )
print ( s. swapcase( ) )
3.2 查找与替换
方法 描述 示例 str.find(sub)返回子串首次出现的索引,未找到返回 -1 "hello".find("l") → 2str.rfind(sub)返回子串最后一次出现的索引,未找到返回 -1 "hello".rfind("l") → 3str.index(sub)类似 find(),但未找到会引发 ValueError "hello".index("l") → 2str.rindex(sub)类似 rfind(),未找到会引发 ValueError "hello".rindex("l") → 3str.count(sub)返回子串出现的次数 "hello".count("l") → 2str.replace(old, new)将字符串中的 old 子串替换为 new "hello".replace("l", "x") → "hexxo"
s = "apple, banana, apple"
print ( s. find( "apple" ) )
print ( s. rfind( "apple" ) )
print ( s. count( "apple" ) )
print ( s. replace( "apple" , "orange" ) )
3.3 去除空白字符
方法 描述 示例 str.strip([chars])移除字符串两端 的指定字符(默认为空白字符) " hello ".strip() → "hello"str.lstrip([chars])移除字符串左侧 的指定字符 " hello ".lstrip() → "hello "str.rstrip([chars])移除字符串右侧 的指定字符 " hello ".rstrip() → " hello"
s = " hello world \n"
print ( s. strip( ) )
print ( s. lstrip( ) )
print ( s. rstrip( ) )
s2 = "xxhelloxx"
print ( s2. strip( 'x' ) )
3.4 分割与连接
方法 描述 示例 str.split(sep=None)按分隔符分割字符串,返回列表 "a,b,c".split(",") → ['a', 'b', 'c']str.rsplit(sep=None)从右侧开始分割 "a,b,c".rsplit(",", 1) → ['a,b', 'c']str.splitlines()按行分割字符串 "line1\nline2".splitlines() → ['line1', 'line2']str.partition(sep)将字符串分为三部分(分隔符前、分隔符、分隔符后) "hello-world".partition("-") → ('hello', '-', 'world')str.rpartition(sep)从右侧开始分区 "hello-world-again".rpartition("-") → ('hello-world', '-', 'again')str.join(iterable)将可迭代对象中的字符串用原字符串连接 "-".join(['a', 'b', 'c']) → "a-b-c"
s = "apple,banana,cherry"
print ( s. split( "," ) )
print ( s. split( "," , 1 ) )
s2 = "user@example.com"
print ( s2. partition( "@" ) )
words = [ "Python" , "is" , "great" ]
print ( " " . join( words) )
3.5 字符串判断(返回布尔值)
方法 描述 示例 str.startswith(prefix)检查字符串是否以指定前缀开头 "hello".startswith("he") → Truestr.endswith(suffix)检查字符串是否以指定后缀结尾 "hello".endswith("lo") → Truestr.isalpha()字符串是否全为字母 "Hello".isalpha() → Truestr.isdigit()字符串是否全为数字 "123".isdigit() → Truestr.isalnum()字符串是否全为字母或数字 "Hello123".isalnum() → Truestr.islower()字符串中的字母是否全为小写 "hello".islower() → Truestr.isupper()字符串中的字母是否全为大写 "HELLO".isupper() → Truestr.isspace()字符串是否全为空白字符 " ".isspace() → Truestr.istitle()字符串是否每个单词首字母大写 "Hello World".istitle() → True
print ( "hello" . startswith( "he" ) )
print ( "123" . isdigit( ) )
print ( "Hello123" . isalnum( ) )
print ( " " . isspace( ) )
3.6 格式化与对齐
方法 描述 示例 str.format(*args, **kwargs)格式化字符串(推荐) "{} {}".format("Hello", "World") → "Hello World"str.ljust(width[, fillchar])左对齐,用指定字符填充至宽度 "hi".ljust(5, '-') → "hi---"str.rjust(width[, fillchar])右对齐 "hi".rjust(5, '-') → "---hi"str.center(width[, fillchar])居中对齐 "hi".center(5, '-') → "--hi-"str.zfill(width)用 0 填充左侧至指定宽度 "42".zfill(5) → "00042"
name = "Alice"
age = 25
print ( "My name is {}, I'm {} years old." . format ( name, age) )
print ( f"My name is { name} , I'm { age} years old." )
s = "text"
print ( s. ljust( 10 , '*' ) )
print ( s. rjust( 10 , '*' ) )
print ( s. center( 10 , '*' ) )
print ( "7" . zfill( 3 ) )
3.7 其他实用方法
方法 描述 示例 len(str)返回字符串长度(内置函数) len("hello") → 5str.encode(encoding)将字符串编码为字节 "hello".encode("utf-8") → b'hello'str.maketrans(x[, y[, z]])创建字符映射表,用于 translate() 见下方示例 str.translate(table)根据映射表替换字符 见下方示例
s = "你好"
print ( s. encode( "utf-8" ) )
trans_table = str . maketrans( "aeiou" , "12345" )
s2 = "hello world"
print ( s2. translate( trans_table) )
4. 总结与最佳实践
字符串不可变 :所有方法都返回新字符串,原字符串不变。优先使用 f-string :Python 3.6+ 推荐使用 f-string 进行字符串格式化,它更简洁、高效。注意 find 与 index 的区别 :find 在未找到时返回 -1,index 会抛出异常,根据场景选择。处理用户输入 :使用 strip() 清理输入两端的空白字符是常见做法。性能考虑 :在循环中拼接大量字符串时,使用 join() 比 += 效率更高。
words = [ "Python" ] * 10000
result = "" . join( words)
result = ""
for w in words:
result += w
掌握这些核心方法,你就能应对绝大多数 Python 字符串处理场景。建议在 IDE 中多练习,加深理解。