Python字符串方法用于处理文本数据,包括大小写转换(如upper、lower)、去除空白(strip)、查找判断(find、startswith)、分割连接(split、join)及类型判断(isdigit、isalpha)等,均返回新字符串。

Python字符串方法是处理文本数据的核心工具。这些方法能帮你修改、查找、分割和格式化字符串,而且不会改变原字符串(因为字符串是不可变类型),而是返回新的字符串结果。
1. 大小写转换
这些方法用于调整字符串的字母大小写:str.upper():将所有字母转为大写str.lower():将所有字母转为小写str.title():每个单词首字母大写str.capitalize():整个字符串首字母大写,其余小写text = "hello world" print(text.upper()) # HELLO WORLD print(text.title()) # Hello World
2. 去除空白字符
常用于清理用户输入或读取文件时的多余空格:str.strip():去掉前后空格(或指定字符)str.lstrip():仅去左边空格str.rstrip():仅去右边空格text = " python " print(text.strip()) # "python"
3. 查找与判断
立即学习“Python免费学习笔记(深入)”;
检查字符串内容是否存在或满足某种条件:str.startswith(prefix):判断是否以某内容开头str.endswith(suffix):判断是否以某内容结尾str.find(sub):查找子串位置,找不到返回-1str.replace(old, new):替换子串filename = "report.pdf"
print(filename.endswith(".pdf")) # True
<p>text = "I like apples"
print(text.find("apples")) # 7
print(text.replace("like", "love")) # I love apples4. 分割与连接
处理列表和字符串之间的转换非常有用:str.split(separator):按分隔符拆成列表"sep".join(list):用指定字符连接列表元素data = "apple,banana,orange"
fruits = data.split(",") # ['apple', 'banana', 'orange']
<p>words = ["hello", "world"]
sentence = " ".join(words) # "hello world"5. 其他实用方法
str.isdigit():判断是否全为数字str.isalpha():判断是否全为字母str.count(sub):统计子串出现次数str.format():格式化字符串(旧方式)age = "18"
print(age.isdigit()) # True
<p>text = "hello hello"
print(text.count("hello")) # 2基本上就这些。掌握这些方法后,处理日常文本操作会变得很简单。注意它们都返回新字符串,记得赋值保存结果。
以上就是Python字符串方法如何使用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号