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

 更新时间:2026年08月12日 09:29:17   作者:何以解忧,唯有..  
想系统掌握Python字符串方法吗,本文汇总了大小写转换、查找替换、分割连接等最常用的Python字符串处理技巧,包含lower、find、split、format等方法示例,让你编码效率翻倍,轻松应对文本处理需求,需要的朋友可以参考下

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 中多练习,加深理解。

以上就是Python字符串(String)常用方法汇总的详细内容,更多关于Python字符串(String)用法的资料请关注脚本之家其它相关文章!

相关文章

  • Django app配置多个数据库代码实例

    Django app配置多个数据库代码实例

    这篇文章主要介绍了Django app配置多个数据库代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12
  • python基础详解之if循环语句

    python基础详解之if循环语句

    这篇文章主要介绍了python基础详解之if循环语句,文中有非常详细的代码示例,对正在学习python的小伙伴们有很好的帮助需要的朋友可以参考下
    2021-04-04
  • python如何处理matlab的mat数据

    python如何处理matlab的mat数据

    这篇文章主要介绍了python如何处理matlab的mat数据,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-05-05
  • python基础之文件操作

    python基础之文件操作

    这篇文章主要介绍了python文件操作,实例分析了Python中返回一个返回值与多个返回值的方法,需要的朋友可以参考下
    2021-10-10
  • python实时获取外部程序输出结果的方法

    python实时获取外部程序输出结果的方法

    今天小编就为大家分享一篇python实时获取外部程序输出结果的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-01-01
  • Pytorch之ToPILImage()不输出图片问题及解决

    Pytorch之ToPILImage()不输出图片问题及解决

    这篇文章主要介绍了Pytorch之ToPILImage()不输出图片问题及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-02-02
  • Python 中的嵌套字典推导的使用及优势

    Python 中的嵌套字典推导的使用及优势

    Python 字典推导是一个强大的工具,允许您从现有的字典创建新的字典,这篇文章主要介绍了Python中的嵌套字典推导,将探索 Python 嵌套字典推导、它的使用以及在 Python 中使用它的优势,需要的朋友可以参考下
    2023-05-05
  • Python中实例化class的执行顺序示例详解

    Python中实例化class的执行顺序示例详解

    这篇文章主要给大家介绍了关于Python中实例化class的执行顺序的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用python具有一定的参考学习价值,需要的朋友们随着小编来一起学习学习吧
    2018-10-10
  • Python实现数据清洗的示例详解

    Python实现数据清洗的示例详解

    这篇文章主要通过五个示例带大家深入了解下Python实现数据清洗的具体方法,文中的示例代码讲解详细,对我们学习Python有一定帮助,需要的可以参考一下
    2022-08-08
  • pandas数据探索之合并数据示例详解

    pandas数据探索之合并数据示例详解

    这篇文章主要为大家介绍了pandas数据探索之合并数据示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-10-10

最新评论