大家在学习Python时,字符串绝对是最常用、最基础的数据类型,无论是处理文本、拼接内容、清洗数据,还是日常开发,都离不开字符串操作。
今天给大家整理了Python字符串最常用的核心函数/方法,按功能分类,清晰好记,新手直接收藏就能用!
一、字符串基础查询与统计
这类函数用来获取字符串信息,不修改原字符串。
1. len(str) —— 获取字符串长度
作用:返回字符串的字符个数(中文、英文、符号都算1个)
s = "Hello Python"
print(len(s)) # 输出:12
2. str.count(sub) —— 统计子串出现次数
作用:查找子字符串在原字符串中出现的次数
s = "apple banana apple"
print(s.count("apple")) # 输出:2
3. str.find(sub) / str.index(sub) —— 查找子串位置
index():找不到直接报错(推荐新手用 find,更安全)
s = "I love Python"
print(s.find("Python")) # 输出:7
print(s.find("Java")) # 输出:-1
4. str.startswith(prefix) / str.endswith(suffix)
作用:判断字符串是否以指定内容开头/结尾,返回布尔值
s = "test.pdf"
print(s.startswith("test")) # True
print(s.endswith(".pdf")) # True
二、字符串大小写转换
一键修改大小写,原字符串不变,返回新字符串。
1. str.upper() —— 全部转大写
"hello".upper() # "HELLO"
2. str.lower() —— 全部转小写
"WORLD".lower() # "world"
3. str.capitalize() —— 首字母大写,其余小写
"python is fun".capitalize() # "Python is fun"
4. str.title() —— 每个单词首字母大写
"hello world".title() # "Hello World"
三、字符串修剪(去空格/换行符)
处理文本时最常用!去掉多余空白字符。
1. str.strip() —— 去掉左右两边的空格、换行、制表符
" Python \n".strip() # "Python"
2. str.lstrip() —— 只去掉左边空白
3. str.rstrip() —— 只去掉右边空白
四、字符串分割与拼接
把字符串拆开、合并,处理文本必备。
1. str.split(sep) —— 按指定符号分割字符串
返回列表,最常用!
s = "a,b,c,d"
print(s.split(",")) # ['a', 'b', 'c', 'd']
2. sep.join(iterable) —— 用符号把序列拼接成字符串
split 的反向操作,超级实用
lst = ["I", "love", "Python"]
print(" ".join(lst)) # "I love Python"
五、字符串替换与修改
1. str.replace(old, new) —— 替换子串
s = "Hello Java"
print(s.replace("Java", "Python")) # "Hello Python"
2. str.center(width) / ljust() / rjust() —— 字符串居中/左对齐/右对齐
"Python".center(10) # ' Python '
六、字符串判断(True / False)
用来校验字符串内容,做表单、数据验证必备。
1. str.isdigit() —— 是否全为数字
"12345".isdigit() # True
"123a".isdigit() # False
2. str.isalpha() —— 是否全为字母
3. str.isalnum() —— 是否由字母+数字组成(无符号、无空格)
4. str.islower() / str.isupper() —— 是否全小写/全大写
七、字符串切片(不是函数,但超级常用)
格式:字符串[起始:结束:步长]
s = "abcdefg"
s[0:3] # "abc"(取前3个)
s[::-1] # "gfedcba"(字符串反转!)
八、高频使用小技巧(必记)
- 去除所有空格:
s.replace(" ", "") - 判断是否包含子串:
if "Python" in s: - 多行字符串:
''' 内容 ''' 或 """ 内容 """
总结(一句话速记)
- 查信息:
len、count、find、startswith、endswith - 判类型:
isdigit、isalpha、isalnum
小寄语
Python字符串操作是编程入门的重中之重,不用死记硬背,多敲几遍代码自然就熟练了!