Python 字符串(str)全方位剖析:从基础入门、方法详解到跨语言对比与知识拓展
本文将深入探讨 Python 中字符串(str)的相关知识,涵盖字符串的定义、创建、基本操作、格式化等内容。同时,会将 Python 字符串与其他常见编程语言(如 Java、C++)中的字符串进行比较,帮助读者更好地理解不同语言中字符串处理的异同。此外,会对class str
进行详细介绍,并对所有字符串方法进行逐一详解,还会对相关知识点进行扩展深化,提供丰富的示例代码和详细的解释,让读者能够全面掌握 Python 字符串的使用。
文章目录
一、Python 字符串(str)基础
1. 字符串的定义
在 Python 中,字符串是由一系列字符组成的不可变序列,可以使用单引号('
)、双引号("
)或三引号('''
或 """
)来表示。
# 使用单引号
str1 = 'Hello, World!'
# 使用双引号
str2 = "Python is great"
# 使用三引号(可以跨多行)
str3 = '''This is a
multi - line string'''
2. 字符串的创建
除了直接使用引号创建字符串外,还可以使用str()
函数将其他数据类型转换为字符串。
num = 123
str_num = str(num)
print(type(str_num)) # <class 'str'>
3. 字符串的基本操作
索引和切片
字符串中的每个字符都有一个索引,索引从 0 开始。可以使用索引来访问单个字符,也可以使用切片来获取子字符串。
s = "Python"
# 访问单个字符
print(s[0]) # P
# 切片操作
print(s[1:3]) # yt
拼接和重复
可以使用+
运算符来拼接字符串,使用*
运算符来重复字符串。
str_a = "Hello"
str_b = "World"
# 拼接
print(str_a + " " + str_b) # Hello World
# 重复
print(str_a * 3) # HelloHelloHello
字符串长度
可以使用len()
函数来获取字符串的长度。
s = "Python"
print(len(s)) # 6
4. 字符串的格式化
Python 提供了多种字符串格式化的方法,如旧式的%
格式化、str.format()
方法和 f - 字符串。
旧式的%
格式化
name = "Alice"
age = 25
print("My name is %s and I'm %d years old." % (name, age))
str.format()
方法
name = "Bob"
age = 30
print("My name is {} and I'm {} years old.".format(name, age))
f - 字符串(Python 3.6+)
name = "Charlie"
age = 35
print(f"My name is {name} and I'm {age} years old.")
二、class str
介绍
在 Python 中,str
是一个内置类,用于表示字符串对象。所有使用引号创建的字符串都是str
类的实例。str
类提供了许多有用的方法来处理字符串。当我们创建一个字符串时,实际上是在创建一个str
类的对象,并且可以调用该对象的各种方法。
s = "example"
print(type(s)) # <class 'str'>
三、Python 字符串(str)方法详解
1. 大小写转换方法
upper()
将字符串中的所有小写字母转换为大写字母。
s = "hello"
print(s.upper()) # HELLO
lower()
将字符串中的所有大写字母转换为小写字母。
s = "WORLD"
print(s.lower()) # world
title()
将字符串中每个单词的首字母转换为大写,其余字母转换为小写。
s = "hello world"
print(s.title()) # Hello World
capitalize()
将字符串的第一个字符转换为大写,其余字符转换为小写。
s = "hello world"
print(s.capitalize()) # Hello world
swapcase()
将字符串中的大写字母转换为小写字母,小写字母转换为大写字母。
s = "HeLlO"
print(s.swapcase()) # hElLo
2. 查找和替换方法
find(sub[, start[, end]])
返回子字符串sub
在字符串中第一次出现的索引,如果未找到则返回 -1。start
和end
参数可选,用于指定查找的起始和结束位置。
s = "hello world"
print(s.find("world")) # 6
rfind(sub[, start[, end]])
与find()
方法类似,但从字符串的右侧开始查找。
s = "hello world world"
print(s.rfind("world")) # 12
index(sub[, start[, end]])
与find()
方法类似,但如果未找到子字符串会抛出ValueError
异常。
s = "hello world"
print(s.index("world")) # 6
rindex(sub[, start[, end]])
与rindex()
方法类似,但从字符串的右侧开始查找,未找到会抛出ValueError
异常。
s = "hello world world"
print(s.rindex("world")) # 12
replace(old, new[, count])
将字符串中的所有old
子字符串替换为new
子字符串。count
参数可选,用于指定替换的次数。
s = "hello world"
print(s.replace("world", "python")) # hello python
3. 去除空白字符方法
strip([chars])
去除字符串首尾的指定字符,默认为去除空白字符(空格、制表符、换行符等)。
s = " hello "
print(s.strip()) # hello
lstrip([chars])
去除字符串左侧的指定字符,默认为去除空白字符。
s = " hello "
print(s.lstrip()) # hello
rstrip([chars])
去除字符串右侧的指定字符,默认为去除空白字符。
s = " hello "
print(s.rstrip()) # hello
4. 分割和连接方法
split(sep=None, maxsplit=-1)
根据指定的分隔符sep
将字符串分割成一个列表。maxsplit
参数可选,用于指定最大分割次数。如果sep
未指定,则默认以空白字符作为分隔符。
s = "hello world"
print(s.split()) # ['hello', 'world']
rsplit(sep=None, maxsplit=-1)
与split()
方法类似,但从字符串的右侧开始分割。
s = "hello world"
print(s.rsplit()) # ['hello', 'world']
splitlines([keepends])
根据换行符将字符串分割成一个列表。keepends
参数可选,为True
时保留换行符,默认为False
。
s = "hello\nworld"
print(s.splitlines()) # ['hello', 'world']
join(iterable)
将可迭代对象中的元素用指定的字符串连接起来。
lst = ['hello', 'world']
s = " ".join(lst)
print(s) # hello world
5. 判断方法
startswith(prefix[, start[, end]])
判断字符串是否以指定的前缀prefix
开头。start
和end
参数可选,用于指定判断的起始和结束位置。
s = "hello world"
print(s.startswith("hello")) # True
endswith(suffix[, start[, end]])
判断字符串是否以指定的后缀suffix
结尾。start
和end
参数可选,用于指定判断的起始和结束位置。
s = "hello world"
print(s.endswith("world")) # True
isalpha()
判断字符串是否只由字母组成。
s = "hello"
print(s.isalpha()) # True
isdigit()
判断字符串是否只由数字组成。
s = "123"
print(s.isdigit()) # True
isalnum()
判断字符串是否只由字母和数字组成。
s = "hello123"
print(s.isalnum()) # True
isspace()
判断字符串是否只由空白字符组成。
s = " "
print(s.isspace()) # True
islower()
判断字符串中的所有字母是否都是小写。
s = "hello"
print(s.islower()) # True
isupper()
判断字符串中的所有字母是否都是大写。
s = "HELLO"
print(s.isupper()) # True
istitle()
判断字符串是否是标题格式(每个单词的首字母大写)。
s = "Hello World"
print(s.istitle()) # True
6. 填充和对齐方法
ljust(width[, fillchar])
返回一个左对齐的字符串,宽度为width
,不足的部分用fillchar
填充,默认为空格。
s = "hello"
print(s.ljust(10, '*')) # hello*****
rjust(width[, fillchar])
返回一个右对齐的字符串,宽度为width
,不足的部分用fillchar
填充,默认为空格。
s = "hello"
print(s.rjust(10, '*')) # *****hello
center(width[, fillchar])
返回一个居中对齐的字符串,宽度为width
,不足的部分用fillchar
填充,默认为空格。
s = "hello"
print(s.center(10, '*')) # **hello***
zfill(width)
返回一个长度为width
的字符串,不足的部分在左侧用 0 填充。
s = "123"
print(s.zfill(5)) # 00123
四、Python 字符串与其他语言字符串的比较
1. Python 与 Java 字符串比较
特性 | Python | Java |
---|---|---|
定义方式 | 单引号、双引号、三引号 | 双引号 |
不可变性 | 字符串是不可变的 | 字符串是不可变的(String 类),但有可变的StringBuilder 和StringBuffer |
格式化 | % 格式化、str.format() 、f - 字符串 | String.format() 方法 |
拼接 | + 运算符 | + 运算符,也可使用StringBuilder 或StringBuffer 进行高效拼接 |
2. Python 与 C++ 字符串比较
特性 | Python | C++ |
---|---|---|
定义方式 | 单引号、双引号、三引号 | std::string 类,使用双引号 |
不可变性 | 字符串是不可变的 | std::string 是可变的 |
格式化 | % 格式化、str.format() 、f - 字符串 | std::stringstream 、std::format (C++20 及以上) |
拼接 | + 运算符 | + 运算符 |
五、相关知识点扩展深化
1. 字符串的编码与解码
在 Python 中,可以使用encode()
方法将字符串编码为字节序列,使用decode()
方法将字节序列解码为字符串。
s = "你好"
# 编码
bytes_s = s.encode('utf - 8')
# 解码
decoded_s = bytes_s.decode('utf - 8')
print(decoded_s) # 你好
总结
本文详细介绍了 Python 中字符串(str)的定义、创建、基本操作和格式化方法,深入讲解了class str
以及所有字符串方法。同时将 Python 字符串与 Java、C++ 中的字符串进行了比较。Python 字符串具有简洁的定义方式和丰富的操作方法,并且提供了多种字符串格式化的手段。在处理字符串时,需要注意字符串的不可变性,以及根据具体需求选择合适的操作方法。此外,还对字符串的编码与解码等相关知识点进行了扩展深化。
TAG:Python、字符串、str、字符串方法、字符串比较、字符串格式化
相关学习资源
- Python 官方文档 - 字符串操作:https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str 。Python 官方提供的关于字符串操作的详细文档,包含了所有字符串方法的介绍和示例。
- Java 官方文档 - String 类:https://docs.oracle.com/javase/8/docs/api/java/lang/String.html 。Java 官方关于
String
类的文档,介绍了 Java 中字符串的各种方法和使用。 - C++ 参考手册 - std::string:https://en.cppreference.com/w/cpp/string/basic_string 。C++ 参考手册中关于
std::string
的详细介绍,包含了std::string
的各种操作和方法。 - Tekin的Python编程秘籍库: Python 实用知识与技巧分享,涵盖基础、爬虫、数据分析等干货 本 Python 专栏聚焦实用知识,深入剖析基础语法、数据结构。分享爬虫、数据分析等热门领域实战技巧,辅以代码示例。无论新手入门还是进阶提升,都能在此收获满满干货,快速掌握 Python 编程精髓。