在 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
四、字符串替换与清洗
1️⃣ replace
s = "hello world"print(s.replace("world", "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
六、字符串格式化方法
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("邮箱格式错误")
九、字符串是不可变的(重点)
s = "hello"s[0] = "H" # 会报错
十、写在最后
字符串方法是 Python 基础中的基础,也是写好 Python 程序的关键能力之一。熟练掌握字符串方法,Python 水平至少提升一个档次。关注我,更多Python编程的技巧和你一起探索!另外博主新开了一个英语学习的号,有兴趣的可以一起关注一下!