第22集:字符串常用方法
本集学习目标
- 掌握字符串大小写转换方法
- 学会字符串的查找和替换
- 掌握字符串的分割和连接
- 学会字符串的去除空白
- 掌握字符串的验证方法
- 通过实际练习掌握字符串方法的使用
大小写转换方法
upper() - 转大写
将字符串中的所有字母转换为大写。
text = "Python Programming"
print(text.upper()) # PYTHON PROGRAMMINGlower() - 转小写
将字符串中的所有字母转换为小写。
text = "Python Programming"
print(text.lower()) # python programmingtitle() - 标题格式
将字符串转换为标题格式(每个单词首字母大写)。
text = "python programming"
print(text.title()) # Python Programmingcapitalize() - 首字母大写
将字符串的第一个字符大写,其余小写。
text = "python programming"
print(text.capitalize()) # Python programmingswapcase() - 大小写互换
将字符串中的大小写互换。
text = "Python Programming"
print(text.swapcase()) # pYTHON pROGRAMMING查找方法
find() - 查找子串
查找子串在字符串中的位置,找不到返回**-1**。
text = "Python Programming"
print(text.find("Python")) # 0
print(text.find("Pro")) # 7
print(text.find("Java")) # -1(找不到)rfind() - 从右边查找
从字符串的右边查找子串。
text = "Python Programming"
print(text.rfind("P")) # 7
print(text.rfind("m")) # 17index() - 查找(找不到报错)
查找子串在字符串中的位置,找不到会报错。
text = "Python Programming"
print(text.index("Python")) # 0
# print(text.index("Java")) # ValueError: substring not foundcount() - 统计出现次数
统计子串在字符串中出现的次数。
text = "Python Programming"
print(text.count("P")) # 2
print(text.count("o")) # 2
print(text.count("Python")) # 1startswith() - 判断开头
判断字符串是否以指定内容开头。
text = "Python Programming"
print(text.startswith("Python")) # True
print(text.startswith("Java")) # Falseendswith() - 判断结尾
判断字符串是否以指定内容结尾。
text = "Python Programming"
print(text.endswith("ing")) # True
print(text.endswith("Python")) # False替换方法
replace() - 替换
将字符串中的子串替换为另一个字符串。
text = "Python Programming"
print(text.replace("Python", "Java")) # Java Programming
print(text.replace("P", "p")) # python programmingreplace() - 限制替换次数
text = "Python Programming"
# 只替换第一个
print(text.replace("P", "X", 1)) # Xython Programming分割方法
split() - 分割字符串
将字符串按照指定分隔符分割成列表。
text = "Python,Java,C++"
print(text.split(",")) # ['Python', 'Java', 'C++']split() - 指定分割次数
text = "Python,Java,C++"
# 只分割一次
print(text.split(",", 1)) # ['Python', 'Java,C++']split() - 分割空白
默认按空白字符(空格、制表符、换行符等)分割。
text = "Python Java C++"
print(text.split()) # ['Python', 'Java', 'C++']rsplit() - 从右边分割
从字符串的右边开始分割。
text = "Python,Java,C++"
print(text.rsplit(",", 1)) # ['Python,Java', 'C++']splitlines() - 按行分割
按换行符分割字符串。
text = """第一行
第二行
第三行"""
print(text.splitlines()) # ['第一行', '第二行', '第三行']连接方法
join() - 连接字符串
将列表中的字符串用指定分隔符连接。
words = ["Python", "Java", "C++"]
result = ",".join(words)
print(result) # Python,Java,C++
result = " ".join(words)
print(result) # Python Java C++join() - 连接字符串
text = "Python Programming"
result = "-".join(text)
print(result) # P-y-t-h-o-n- -P-r-o-g-r-a-m-m-i-n-g去除空白方法
strip() - 去除两端空白
去除字符串两端的空白字符。
text = " Python Programming "
print(text.strip()) # Python Programminglstrip() - 去除左边空白
去除字符串左边的空白字符。
text = " Python Programming"
print(text.lstrip()) # Python Programmingrstrip() - 去除右边空白
去除字符串右边的空白字符。
text = "Python Programming "
print(text.rstrip()) # Python Programmingstrip() - 去除指定字符
去除字符串两端的指定字符。
text = "===Python==="
print(text.strip("=")) # Python验证方法
isdigit() - 判断数字
判断字符串是否只包含数字。
print("123".isdigit()) # True
print("12.3".isdigit()) # False
print("abc".isdigit()) # Falseisalpha() - 判断字母
判断字符串是否只包含字母。
print("Python".isalpha()) # True
print("Python3".isalpha()) # False
print("123".isalpha()) # Falseisalnum() - 判断字母或数字
判断字符串是否只包含字母或数字。
print("Python3".isalnum()) # True
print("Python3!".isalnum()) # Falseisspace() - 判断空白
判断字符串是否只包含空白字符。
print(" ".isspace()) # True
print(" a ".isspace()) # Falseislower() - 判断小写
判断字符串是否只包含小写字母。
print("python".islower()) # True
print("Python".islower()) # Falseisupper() - 判断大写
判断字符串是否只包含大写字母。
print("PYTHON".isupper()) # True
print("Python".isupper()) # Falseistitle() - 判断标题格式
判断字符串是否符合标题格式。
print("Python Programming".istitle()) # True
print("python programming".istitle()) # False对齐方法
center() - 居中对齐
将字符串居中对齐,用指定字符填充。
text = "Python"
print(text.center(20)) # " Python "
print(text.center(20, "=")) # "=======Python======="ljust() - 左对齐
将字符串左对齐,用指定字符填充。
text = "Python"
print(text.ljust(20)) # "Python "
print(text.ljust(20, "=")) # "Python==============="rjust() - 右对齐
将字符串右对齐,用指定字符填充。
text = "Python"
print(text.rjust(20)) # " Python"
print(text.rjust(20, "=")) # "===============Python"实际应用案例
案例1:用户名规范化
username = input("请输入用户名:")
# 统一转为小写
username = username.lower()
# 去除两端空白
username = username.strip()
print(f"规范化后的用户名:{username}")案例2:密码强度检查
password = input("请输入密码:")
# 检查长度
if len(password) < 8:
print("密码长度至少8位")
else:
# 检查是否包含数字
has_digit = any(char.isdigit() for char in password)
# 检查是否包含字母
has_alpha = any(char.isalpha() for char in password)
if has_digit and has_alpha:
print("密码强度:强")
else:
print("密码强度:弱(需要包含字母和数字)")案例3:处理CSV数据
csv_data = "张三,20,男\n李四,25,女\n王五,30,男"
# 按行分割
lines = csv_data.split("\n")
for line in lines:
# 按逗号分割
parts = line.split(",")
if len(parts) == 3:
name, age, gender = parts
print(f"姓名:{name},年龄:{age},性别:{gender}")案例4:文件名处理
filename = " my_document.PDF "
# 去除空白
filename = filename.strip()
# 转小写
filename_lower = filename.lower()
# 分割文件名和扩展名
name, extension = filename_lower.rsplit(".", 1)
print(f"文件名:{name}")
print(f"扩展名:{extension}")本集小结
- 大小写转换:upper(), lower(), title(), capitalize(), swapcase()
- 查找方法:find(), rfind(), index(), count(), startswith(), endswith()
- 替换方法:replace()
- 分割方法:split(), rsplit(), splitlines()
- 连接方法:join()
- 去除空白:strip(), lstrip(), rstrip()
- 验证方法:isdigit(), isalpha(), isalnum(), isspace(), islower(), isupper(), istitle()
- 对齐方法:center(), ljust(), rjust()
课后练习
练习1:大小写转换
将字符串"PYTHON programming"转换为:
- 全大写
- 全小写
- 标题格式
练习2:查找和替换
在字符串"Python Programming"中:
- 查找"Pro"的位置
- 将"Python"替换为"Java"
练习3:分割和连接
将字符串"Python,Java,C++"分割成列表,再用"|"连接。
练习4:验证输入
验证用户输入是否为有效的数字(只包含数字)。
练习5:格式化输出
将列表["Python", "Java", "C++"]格式化为对齐输出。
下集预告
下一集我们将学习第23集:列表基础操作。列表是Python中最常用的数据结构之一,可以存储多个元素。
敬请期待!