Python字符串函数大全:从入门到进阶175


Python 作为一门功能强大的编程语言,其内置的字符串函数提供了丰富的操作字符串的功能,能够满足各种文本处理的需求。本文将深入浅出地讲解 Python 中常用的字符串函数,涵盖字符串的创建、修改、查找、替换、分割等多个方面,并辅以代码示例,帮助读者更好地理解和运用这些函数。

一、创建字符串

Python 中创建字符串非常简单,可以使用单引号(' ')、双引号(" ")或三引号(''' ''', """ """)来定义字符串。三引号可以用来创建多行字符串。
str1 = 'Hello'
str2 = "World"
str3 = '''This is a
multiline string'''

二、访问字符串字符

Python 字符串是不可变的序列,这意味着你不能直接修改字符串中的字符。可以使用索引来访问字符串中的单个字符或子字符串。索引从 0 开始,-1 代表最后一个字符。
str = "Python"
print(str[0]) # 输出:P
print(str[-1]) # 输出:n
print(str[1:4]) # 输出:yth (从索引1到4,不包括4)


三、常用字符串函数

以下列举一些 Python 中常用的字符串函数,并附带详细解释和示例:
len(string): 返回字符串的长度。

str = "Hello"
print(len(str)) # 输出:5

upper(): 将字符串转换为大写。

str = "hello"
print(()) # 输出:HELLO

lower(): 将字符串转换为小写。

str = "HELLO"
print(()) # 输出:hello

capitalize(): 将字符串的首字母大写,其余字母小写。

str = "hello world"
print(()) # 输出:Hello world

title(): 将字符串中每个单词的首字母大写。

str = "hello world"
print(()) # 输出:Hello World

strip(), lstrip(), rstrip(): 去除字符串两端、左侧或右侧的空格或指定字符。

str = " hello world "
print(()) # 输出:hello world
print(()) # 输出:hello world
print(()) # 输出: hello world
str2 = "*hello*"
print(("*")) # 输出:hello

find(substring, start, end), rfind(substring, start, end): 从左/右查找子字符串,返回其起始索引,找不到则返回 -1。

str = "hello world"
print(("world")) # 输出:6
print(("o")) # 输出:7

index(substring, start, end), rindex(substring, start, end): 与find()/rfind()类似,但找不到子字符串时会引发异常。

str = "hello world"
print(("world")) # 输出:6
#print(("xyz")) # 会引发ValueError异常

count(substring, start, end): 统计子字符串在字符串中出现的次数。

str = "hello world hello"
print(("hello")) # 输出:2

replace(old, new, count): 将字符串中的旧子字符串替换为新子字符串。

str = "hello world"
print(("world", "python")) # 输出:hello python

split(sep, maxsplit): 根据分隔符将字符串分割成列表。

str = "apple,banana,orange"
print((",")) # 输出:['apple', 'banana', 'orange']

join(iterable): 将可迭代对象中的元素连接成一个字符串。

list1 = ['apple', 'banana', 'orange']
print(",".join(list1)) # 输出:apple,banana,orange

startswith(prefix), endswith(suffix): 检查字符串是否以特定前缀或后缀开头或结尾。

str = "hello world"
print(("hello")) # 输出:True
print(("world")) # 输出:True

isalnum(), isalpha(), isdigit(), isspace(): 检查字符串是否仅包含字母数字字符、字母字符、数字字符或空格字符。

str = "HelloWorld123"
print(()) # 输出:True


四、总结

本文介绍了 Python 中常用的字符串函数,这些函数能够帮助你高效地处理各种字符串操作。 熟练掌握这些函数,能够显著提高你的 Python 编程效率。 建议读者多实践,通过编写代码来加深对这些函数的理解和运用。 此外,Python 的官方文档也是学习和参考的良好资源。

2025-05-19


上一篇:Python序列函数详解:列表、元组、字符串的高效操作

下一篇:Python 函数进阶:15道练习题助你精通函数式编程