Python 字符串(String)常用方法总结

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())      # python string
print(s.upper())      # PYTHON STRING
print(s.capitalize()) # Python string
print(s.title())      # Python String
print(s.swapcase())   # PyThOn StRiNg

3.2 查找与替换

方法描述示例
str.find(sub)返回子串首次出现的索引,未找到返回 -1"hello".find("l")2
str.rfind(sub)返回子串最后一次出现的索引,未找到返回 -1"hello".rfind("l")3
str.index(sub)类似 find(),但未找到会引发 ValueError"hello".index("l")2
str.rindex(sub)类似 rfind(),未找到会引发 ValueError"hello".rindex("l")3
str.count(sub)返回子串出现的次数"hello".count("l")2
str.replace(old, new)将字符串中的 old 子串替换为 new"hello".replace("l", "x")"hexxo"
s = "apple, banana, apple"
print(s.find("apple"))        # 0
print(s.rfind("apple"))       # 14
print(s.count("apple"))       # 2
print(s.replace("apple", "orange"))  # orange, banana, 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())   # "hello world"
print(s.lstrip())  # "hello world  \n"
print(s.rstrip())  # "  hello world"

s2 = "xxhelloxx"
print(s2.strip('x'))  # "hello"

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(","))          # ['apple', 'banana', 'cherry']
print(s.split(",", 1))       # ['apple', 'banana,cherry'] 最大分割次数

# 分区
s2 = "user@example.com"
print(s2.partition("@"))     # ('user', '@', 'example.com')

# 连接
words = ["Python", "is", "great"]
print(" ".join(words))       # Python is great

3.5 字符串判断(返回布尔值)

方法描述示例
str.startswith(prefix)检查字符串是否以指定前缀开头"hello".startswith("he")True
str.endswith(suffix)检查字符串是否以指定后缀结尾"hello".endswith("lo")True
str.isalpha()字符串是否全为字母"Hello".isalpha()True
str.isdigit()字符串是否全为数字"123".isdigit()True
str.isalnum()字符串是否全为字母或数字"Hello123".isalnum()True
str.islower()字符串中的字母是否全为小写"hello".islower()True
str.isupper()字符串中的字母是否全为大写"HELLO".isupper()True
str.isspace()字符串是否全为空白字符" ".isspace()True
str.istitle()字符串是否每个单词首字母大写"Hello World".istitle()True
print("hello".startswith("he"))   # True
print("123".isdigit())            # True
print("Hello123".isalnum())       # True
print("   ".isspace())            # True

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))
# f-string (Python 3.6+ 更简洁)
print(f"My name is {name}, I'm {age} years old.")

# 对齐
s = "text"
print(s.ljust(10, '*'))  # text******
print(s.rjust(10, '*'))  # ******text
print(s.center(10, '*')) # ***text***
print("7".zfill(3))      # 007

3.7 其他实用方法

方法描述示例
len(str)返回字符串长度(内置函数)len("hello")5
str.encode(encoding)将字符串编码为字节"hello".encode("utf-8")b'hello'
str.maketrans(x[, y[, z]])创建字符映射表,用于 translate()见下方示例
str.translate(table)根据映射表替换字符见下方示例
# 编码
s = "你好"
print(s.encode("utf-8"))  # b'\xe4\xbd\xa0\xe5\xa5\xbd'

# 使用 maketrans 和 translate 进行字符替换
trans_table = str.maketrans("aeiou", "12345")
s2 = "hello world"
print(s2.translate(trans_table))  # h2ll4 w4rld

4. 总结与最佳实践

  1. 字符串不可变:所有方法都返回新字符串,原字符串不变。
  2. 优先使用 f-string:Python 3.6+ 推荐使用 f-string 进行字符串格式化,它更简洁、高效。
  3. 注意 findindex 的区别find 在未找到时返回 -1index 会抛出异常,根据场景选择。
  4. 处理用户输入:使用 strip() 清理输入两端的空白字符是常见做法。
  5. 性能考虑:在循环中拼接大量字符串时,使用 join()+= 效率更高。
# 高效拼接示例
words = ["Python"] * 10000
# 推荐
result = "".join(words)
# 不推荐(性能差)
result = ""
for w in words:
    result += w

掌握这些核心方法,你就能应对绝大多数 Python 字符串处理场景。建议在 IDE 中多练习,加深理解。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值