1. 定义与创建
字符串(String)是 Python 中的基本数据类型之一,用于表示文本数据。字符串是由字符组成的不可变序列,可以使用单引号(‘)、双引号(")或三引号(’‘’ 或 “”")来定义。
单引号字符串
single_quote_str = 'Hello, world!'
print(single_quote_str)
双引号字符串
double_quote_str = "Python is awesome."
print(double_quote_str)
三引号字符串
triple_quote_str = '''This is a
multi-line string.'''
print(triple_quote_str)
2. 字符串的不可变性
字符串在 Python 中是不可变的,这意味着一旦创建,字符串的内容不能被修改。如果尝试修改字符串中的某个字符,会引发错误。
示例
my_str = "hello"
# my_str[0] = 'H' # TypeError: 'str' object does not support item assignment
3. 字符串的常用操作
3.1 索引与切片
字符串可以通过索引访问单个字符,索引从 0 开始。同时,也可以使用切片操作获取字符串的子序列。
索引
my_str = "Python"
print(my_str[0]) # 输出: P
print(my_str[-1]) # 输出: n
切片
my_str = "Python"
print(my_str[0:3]) # 输出: Pyt
print(my_str[3:]) # 输出: hon
print(my_str[:4]) # 输出: Pyth
print(my_str[-3:]) # 输出: hon
3.2 连接字符串
可以使用加号(+)将多个字符串连接在一起。
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # 输出: Hello World
3.3 重复字符串
使用乘号(*)可以将字符串重复指定次数。
my_str = "Python"
print(my_str * 3) # 输出: PythonPythonPython
3.4 字符串长度
使用 len()
函数可以获取字符串的长度。
my_str = "Python"
print(len(my_str)) # 输出: 6
3.5 字符串方法
Python 提供了许多内置的字符串方法,用于对字符串进行操作和处理。
大小写转换
my_str = "Python"
print(my_str.upper()) # 输出: PYTHON
print(my_str.lower()) # 输出: python
去除空白字符
my_str = " Hello, World! "
print(my_str.strip()) # 输出: Hello, World!
print(my_str.lstrip()) # 输出: Hello, World!
print(my_str.rstrip()) # 输出: Hello, World!
查找与替换
my_str = "Hello, World!"
print(my_str.find("World")) # 输出: 7
print(my_str.replace("World", "Python")) # 输出: Hello, Python!
分割与连接
my_str = "apple,banana,cherry"
my_list = my_str.split(",") # 分割为列表
print(my_list) # 输出: ['apple', 'banana', 'cherry']
new_str = "-".join(my_list) # 使用 "-" 连接列表
print(new_str) # 输出: apple-banana-cherry
4. 格式化字符串
Python 提供了多种字符串格式化的方法,用于将变量或数据插入到字符串中。
4.1 使用 %
格式化
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))
4.2 使用 str.format()
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
4.3 使用 f-string(Python 3.6+)
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
5. 字符串编码与解码
在 Python 中,字符串默认使用 UTF-8 编码。可以通过 encode()
和 decode()
方法进行编码和解码操作。
编码
my_str = "你好"
encoded_str = my_str.encode("utf-8")
print(encoded_str) # 输出: b'\xe4\xbd\xa0\xe5\xa5\xbd'
解码
encoded_str = b'\xe4\xbd\xa0\xe5\xa5\xbd'
decoded_str = encoded_str.decode("utf-8")
print(decoded_str) # 输出: 你好
6. 总结
字符串是 Python 中非常重要的数据类型,用于处理文本数据。它具有不可变性,提供了丰富的操作方法和格式化方式,能够满足各种文本处理需求。
本栏文章会持续同步到下边公众号