Python 以其简洁易懂的语法和强大的字符串处理能力而闻名。掌握字符串函数是进行文本分析、数据清洗和自然语言处理等任务的基础。
1. `lower()` 和 `upper()`
将字符串转换为小写或大写
text?=?"Hello?World"
lower_text?=?text.lower()??#?"hello?world"
upper_text?=?text.upper()??#?"HELLO?WORLD"
2. `strip()`、`lstrip()` 和 `rstrip()`
去除字符串开头、结尾或两端的空格(或指定字符)
text?=?"??Hello?World??"
stripped_text?=?text.strip()??#?"Hello?World"
lstripped_text?=?text.lstrip()??#?"Hello?World??"
rstripped_text?=?text.rstrip()??#?"??Hello?World"
3. `split()`
将字符串按照指定分隔符分割成列表
text?=?"apple,banana,orange"
fruits?=?text.split(",")??#?['apple',?'banana',?'orange']
4. `join()`
将列表中的字符串按照指定分隔符连接成一个字符串。
fruits?=?['apple',?'banana',?'orange']
text?=?",?".join(fruits)??#?"apple,?banana,?orange"
5. `replace()`
将字符串中的指定子串替换成另一个子串。
text?=?"Hello?World"
new_text?=?text.replace("World",?"Python")??#?"Hello?Python"
6. `find()` 和 `index()`
查找指定子串在字符串中第一次出现的位置
find() 未找到返回 -1,index() 未找到抛出 ValueError 异常。
text?=?"Hello?World"
position?=?text.find("World")??#?6
position?=?text.index("World")??#?6
7. `startswith()` 和 `endswith()`
判断字符串是否以指定子串开头或结尾
text?=?"Hello?World"
is_start?=?text.startswith("Hello")??#?True
is_end?=?text.endswith("World")??#?True
8. `isdigit()`、`isalpha()` 和 `isalnum()`
判断字符串是否只包含数字、字母或数字字母组合。
text1?=?"12345"
text2?=?"abcde"
text3?=?"123abc"
text1.isdigit()??#?True
text2.isalpha()??#?True
text3.isalnum()??#?True
9. `count()`
统计指定子串在字符串中出现的次数
text?=?"Hello?World?World"
count?=?text.count("World")??#?2
10. `format()`
格式化字符串,将变量或值插入到字符串中。
name?=?"Alice"
age?=?30
text?=?"My?name?is?{}?and?I?am?{}?years?old.".format(name,?age)??#?"My?name?is?Alice?and?I?am?30?years?old."
以上 10 个 Python 字符串函数只是冰山一角,Python 还有许多其他强大的字符串处理工具等待你去探索。熟练掌握这些函数,将大大提升你的编程效率和代码质量。