在Python中,文本序列类型主要指的是字符串(str
),它是一种不可变的序列,用于表示Unicode文本。Python 3中的字符串本质上是Unicode字符序列,这使得它能够支持全球各种语言的文本处理。
字符串的核心特性
- 不可变性:字符串一旦创建,其内容不可修改。任何看似修改字符串的操作,实际上都会创建一个新的字符串对象。
- 序列操作:作为序列类型,字符串支持多种序列操作,如索引、切片、连接、重复等。
- Unicode支持:Python 3的字符串直接支持Unicode编码,可表示全球各种语言的字符。
字符串的常用操作
下面是一些字符串常见操作的示例:
# 字符串创建
s = "Hello, World!"
print(s) # 输出: Hello, World!
# 索引操作
print(s[0]) # 输出: H
print(s[-1]) # 输出: !
# 切片操作 [start:stop:step]
print(s[0:5]) # 输出: Hello
print(s[7:]) # 输出: World!
print(s[::2]) # 输出: Hlo ol!
# 字符串连接
s1 = "Hello"
s2 = "World"
s3 = s1 + ", " + s2 + "!"
print(s3) # 输出: Hello, World!
# 字符串重复
print(s1 * 3) # 输出: HelloHelloHello
# 字符串长度
print(len(s)) # 输出: 13
# 字符串查找
print(s.find("World")) # 输出: 7 (第一次出现的索引)
print(s.count("l")) # 输出: 3 (字符"l"出现的次数)
# 字符串替换
print(s.replace("World", "Python")) # 输出: Hello, Python!
# 字符串分割
words = s.split(", ")
print(words) # 输出: ['Hello', 'World!']
# 字符串大小写转换
print(s.upper()) # 输出: HELLO, WORLD!
print(s.lower()) # 输出: hello, world!
print(s.capitalize()) # 输出: Hello, world!
# 字符串去除空白
s_with_spaces = " Hello, World! "
print(s_with_spaces.strip()) # 输出: Hello, World!
print(s_with_spaces.lstrip()) # 输出: Hello, World!
print(s_with_spaces.rstrip()) # 输出: Hello, World!
# 字符串格式化
name = "Alice"
age = 30
print(f"My name is {name} and I'm {age} years old.") # 输出: My name is Alice and I'm 30 years old.
print("My name is {} and I'm {} years old.".format(name, age)) # 输出: My name is Alice and I'm 30 years old.
print("My name is {0} and I'm {1} years old. {0}".format(name, age)) # 输出: My name is Alice and I'm 30 years old. Alice
# 字符串编码与解码
s_encoded = s.encode('utf-8') # 编码为字节串
print(s_encoded) # 输出: b'Hello, World!'
s_decoded = s_encoded.decode('utf-8') # 解码为字符串
print(s_decoded) # 输出: Hello, World!
# 判断字符串内容
print(s.isalpha()) # 输出: False (包含非字母字符)
print(s.isdigit()) # 输出: False (包含非数字字符)
print(s.isalnum()) # 输出: False (包含非字母数字字符)
print(s.startswith("Hello")) # 输出: True
print(s.endswith("World!")) # 输出: True
字符串格式化方法
Python提供了多种字符串格式化方法:
- f-string(Python 3.6+):
name = "Bob"
age = 25
print(f"{name} is {age} years old.") # 输出: Bob is 25 years old.
- str.format():
print("{} is {} years old.".format(name, age)) # 输出: Bob is 25 years old.
- 旧式%格式化:
print("%s is %d years old." % (name, age)) # 输出: Bob is 25 years old.
多行字符串
使用三重引号(单引号或双引号)可以创建多行字符串:
multiline = """
This is a
multiline
string.
"""
print(multiline)
原始字符串
原始字符串通过在字符串前加r
或R
来创建,其中的转义字符会被直接当作普通字符处理:
raw_string = r"C:\Users\Documents"
print(raw_string) # 输出: C:\Users\Documents
总结
Python的字符串(str
)是一种强大且灵活的文本序列类型,支持Unicode编码,提供了丰富的内置方法来处理文本数据。由于其不可变性,对字符串的任何修改都会创建新的字符串对象,这在处理大量文本时需要注意性能问题。