当前位置:首页>python>Python基础|字符串内置方法详解:这些方法你每天都在用

Python基础|字符串内置方法详解:这些方法你每天都在用

  • 2026-10-21 13:27:59
Python基础|字符串内置方法详解:这些方法你每天都在用

在 Python 中,字符串是使用频率最高的数据类型之一。读文件、处理用户输入、解析日志、拼接提示信息,几乎都离不开字符串。

很多新手在写代码时,习惯用“笨办法”处理字符串,其实 Python 已经为我们准备好了大量高效、易用的字符串内置方法。

本文将系统梳理最常用的字符串方法,帮你写出更简洁、更优雅的 Python 代码。

一、什么是字符串内置方法?

字符串是 str 类型,Python 为它内置了大量方法,用来完成:
  • 查找与判断
  • 大小写转换
  • 拆分与拼接
  • 格式化与清洗
示例:
s = "hello world"print(s.upper()) # HELLO WORLD

二、大小写相关方法(最常用)

1️⃣ upper / lower

s = "Python"print(s.upper()) # PYTHONprint(s.lower()) # python
常用于:用户输入统一格式,不区分大小写的比较

2️⃣ capitalize / title

print("hello python".capitalize()) # Hello pythonprint("hello python".title()) # Hello Python

三、查找与判断类方法

1️⃣ find / index

s = "linux shell script"print(s.find("shell")) # 返回索引print(s.find("python")) # -1
区别:find 找不到返回 -1,index 找不到会报错

2️⃣ startswith / endswith

filename = "test.py"print(filename.endswith(".py"))
非常适合做文件类型判断。

3️⃣ is 系列方法

s = "123"print(s.isdigit()) #Trueprint(s.isalpha()) # False
常见方法:
  • isdigit()
  • isalpha()
  • isalnum()
  • isspace()

四、字符串替换与清洗

1️⃣ replace

s = "hello world"print(s.replace("world", "python"))
输出:
hello python

2️⃣ strip / lstrip / rstrip

s = "  hello  "print(s.strip()) # hello 移除空白字符
用于:
清理用户输入
去掉日志中的空格和换行

五、拆分与拼接(非常重要)

1️⃣ split

line = "192.168.1.1"ip = line.split(".")print(ip) # ['192', '168', '1', '1']

2️⃣ join(初学者常忽略)

items = ["2024", "01", "01"]date = "-".join(items)print(date) # 2024-01-01
⚠️ join 的主体是分隔符,不是列表。

六、字符串格式化方法

1️⃣ format(推荐掌握)

name = "Tom"age = 18print("姓名:{},年龄:{}".format(name, age))

2️⃣ f-string(Python 3.6+ 强烈推荐)

print(f"姓名:{name},年龄:{age}")
简洁、可读性强,是目前主流写法。

七、计数与长度相关

1️⃣ count

s = "banana"print(s.count("a"))

2️⃣ len(不是方法)

print(len(s)) # 不是属于字符串的方法

八、一个综合实战示例

需求:处理用户输入的邮箱地址,判断是否合法。
email = input("请输入邮箱:").strip().lower()if "@" in email and email.endswith(".com"):    print("邮箱格式基本正确")else:    print("邮箱格式错误")
这里用到了:
  • strip
  • lower
  • endswith
  • 成员判断

九、字符串是不可变的(重点)

s = "hello"s[0] = "H" # 会报错
字符串的每次修改,都会生成新对象。

十、写在最后

字符串方法是 Python 基础中的基础,也是写好 Python 程序的关键能力之一。
建议你:
  • 多查官方文档
  • 多在实际代码中使用
  • 少手写“低效逻辑”
熟练掌握字符串方法,Python 水平至少提升一个档次。
关注我,更多Python编程的技巧和你一起探索!另外博主新开了一个英语学习的号,有兴趣的可以一起关注一下!

最新文章

随机文章