***本文由AI辅助生成***
字符串在Python中是不可变的对象,它们支持许多内建的操作,用于格式化、搜索、替换以及分割字符串。以下是一些常见和实用的字符串操作方法:
使用 in
关键字检查子字符串是否存在,或者使用 find()
和 index()
方法:
text = "Hello, world!"
if "world" in text:
print("Found it!")
position = text.find("world") # 7
print(position) # 输出第一个匹配项的位置
# index() 类似于 find(),但如果没有找到会抛出 ValueError
position = text.index("universe") # 将引发异常
使用 format()
或 f-string(Python 3.6+)进行格式化,此外也可以使用format_map()
name = "Alice"
age = 30
# format()
print("My name is {} and I am {} years old.".format(name, age))
# f-string
print(f"My name is {name} and I am {age} years old.")
# format_map()
mapping = {"name": "Alice", "age": 30}
print("My name is {name} and I am {age} years old.".format_map(mapping))
split()
:按指定字符,将字符串分割成多份,并放到数组中。
partition()
和 rpartition()
:这两个方法分别从左边或右边查找第一次出现的字符,并返回一个元组包含三部分:前缀、字符本身、后缀。
注:示例中展示的字符为 “-”,也可以使用其他字符或英文字母。
splitlines()
:按换行符,将字符串分割(可处理不同类型的换行符)。
# split()
text = "apple, banana, cherry"
fruits = text.split(", ")
print(fruits) # ['apple', 'banana', 'cherry']
# partition()
text = "hello-world-example"
prefix, sep, suffix = text.partition("-")
print(prefix, sep, suffix) # hello - world-example
# rpartition()
_, _, example = text.rpartition("-")
print(example) # example
# splitlines()
text = "line1\nline2\rline3\r\nline4"
lines = text.splitlines()
print(lines) # ['line1', 'line2', 'line3', 'line4']
使用 +
或者 join()
方法将多个字符串组合在一起。
fruits = ['apple', 'banana', 'cherry']
# +
joined_text = fruits[0] + ', ' + fruits[1] + ', ' + fruits[2]
print(joined_text) # "apple, banana, cherry"
# join()
joined_text = ', '.join(fruits)
print(joined_text) # "apple, banana, cherry"
replace()
:替换字符串中的部分,用参数2替换掉参数1。
expandtabs()
:替换字符串中的制表符 \t
为指定数量的空格。
maketrans()
和 translate()
:创建翻译表,然后使用此表来替换字符串中的字符。
# replace()
old_str = "Hello, world!"
new_str = old_str.replace("world", "Earth")
print(new_str) # "Hello, Earth!"
# expandtabs()
text = "hello\tworld"
print(text.expandtabs(4)) # "hello world"
# maketrans() && translate()
trans_table = str.maketrans("abc", "xyz")
translated = "abc def abc".translate(trans_table)
print(translated) # xyz def xyz
使用 len()
函数获取字符串的长度:
text = "Hello, world!"
length = len(text)
print(length) # 13
upper()
:将字符串转换为大写
lower()
或 casefold()
:将字符串转换为小写
swapcase()
:将字符串中大写字母转换为小写,将小写字母转换为大写
text = "Hello, World!"
print(text.upper()) # "HELLO, WORLD!"
print(text.lower()) # "hello, world!"
print(text.casefold()) # "hello, world!"
print(text.swapcase()) # "hELLO, wORLD!"
# casefold() 比 lower() 更强大,不仅可以转换 ASCII 编码中的大写字符,还可以转换其他语言中的大写字符。如德语。
# 但对于大多数只包含英文字母的情况,lower()方法就足够了。
text = "ß"
print(text.lower()) # ß
print(text.casefold()) # ss
startswith(x)
:字符串是否以 x 开头。
endswith(x)
:字符串是否以 x 结束。
text = "Hello, world!"
starts_with_hello = text.startswith("Hello")
ends_with_world = text.endswith("world") # 实际结尾为 world!
print(starts_with_hello, ends_with_world) # True False
使用 strip()
, lstrip()
, rstrip()
方法去除字符串两端的空白:
text = " Hello, world! "
print(text.strip()) # "Hello, world!"
print(text.lstrip()) # "Hello, world! "
print(text.rstrip()) # " Hello, world!"
使用切片操作提取字符串的一部分:
s = "Hello, World!"
print(s[0:5]) # 输出 "Hello",从索引0开始到索引5(不包含)
print(s[:5]) # 输出 "Hello",等同于s[0:5]
print(s[7:]) # 输出 "World!",从索引7开始到字符串末尾
print(s[:]) # 输出 "Hello, World!"
print(s[-6:]) # 输出 "World!",从倒数第6个字符开始到末尾
print(s[:-1]) # 输出 "Hello, World",不包含最后一个字符
# 指定步长
s = "abcdefghij"
print(s[0:10:2]) # 输出 "acegi",从索引0到10(不包含),步长为2
print(s[::-1]) # 输出 "jihgfedcba",反转整个字符串
print(s[8:0:-2]) # 输出 "igec",从索引8开始到索引0(不包含),步长为 - 2
isalpha()
:是否每个字符都为英文字母
isdigit()
:是否每个字符都为数字
isspace()
:是否每个字符都为空格
isalnum()
:是否每个字符都为英文字母或数字
islower()
:是否每个字符都为小写字母
isupper()
:是否每个字符都为大写字母
print("Hello".isalpha()) # True
print("123.45".isdigit()) # False
print("12345".isdigit()) # True
print(" ".isspace()) # True
print("Hello123".isalnum()) # True
print("Hello.123".isalnum()) # False
zfill()
在字符串左端填充零至指定长度:
num = "23"
padded_num = num.zfill(5)
print(padded_num) # 00023
encode()
:将字符串转换为指定编码格式的字节序列,如’utf-8’、‘utf-16’、'ascii’等。
decode()
:将字节序列转换为Unicode字符串,即解码字节为字符串。
text = "hello"
byte_seq = text.encode('utf-8')
print(byte_seq.decode('utf-8'))
虽然不是字符串内建方法,但经常与字符串操作一起使用:
import re
# 简单匹配
pattern = r'\d+' # 匹配一个或多个数字
text = "There are 12 apples."
match = re.search(pattern, text)
if match:
print("Found a number:", match.group()) # Found a number: 12
# 查找所有匹配
text = "Apples cost $3 and bananas cost $2.50."
prices = re.findall(r'\$\d+\.*\d*', text)
print(prices) # ['$3', '$2.50']
# 替换内容
text = "Call me at 123-456-7890"
new_text = re.sub(r'\d+', 'XXX', text) # 匹配一个或多个数字,并将匹配到的项替换为 XXX
print(new_text) # Call me at XXX-XXX-XXX
# 分组
phone = "123-456-7890"
pattern = r'(\d{3})-(\d{3})-(\d{4})'
match = re.match(pattern, phone)
if match:
area_code, prefix, line_number = match.groups()
print(area_code, prefix, line_number) # 123 456 7890
# 非贪婪匹配
# 使用问号 ? 来表示“尽可能少”的匹配
html = "text
"
pattern = r'<.*?>'
match = re.search(pattern, html)
print(match.group()) #
# 特殊字符转义
text = "path/to/file*name"
pattern = r'\*' # 注意 * 必须被转义
match = re.search(pattern, text)
print(bool(match)) # True
# 量词
# * 表示任意次重复,+ 至少一次,? 最多一次,{m,n} 表示 m 到 n 次重复
text = "aaabbbbcc"
pattern = r'a*b+c' # 匹配 bccc 或 abbbbbc 或 aaaaabbbbccc 等
matches = re.findall(pattern, text)
print(matches) # ['aaabbbbc']
# 字符集
text = "Hello, my email is [email protected]"
pattern = r'[a-zA-Z]+@[a-zA-Z]+\.[a-zA-Z]+'
match = re.search(pattern, text)
print(match.group()) # [email protected]
# 断言
# ^ 和 $ 分别表示字符串的开头和结尾
text = "end of string"
pattern = r'^end' # 以 end 开头
match = re.search(pattern, text)
print(bool(match)) # True
以上列出的方法涵盖了字符串处理的更多方面,可以帮助你在处理复杂文本时有更多选择。熟练掌握这些方法可以使你的代码更加高效和清晰。