Python 的字符串(str
)类型提供了许多方法,用于操作和处理字符串数据。以下是一些常用的字符串方法及其示例:
方法示例:
-
str.lower()
:将字符串中的所有字符转换为小写。s = "Hello, World!"
print(s.lower()) # 输出: hello, world!
-
str.upper()
:将字符串中的所有字符转换为大写。python复制代码
s = "Hello, World!"
print(s.upper()) # 输出: HELLO, WORLD!
-
str.capitalize()
:将字符串的第一个字符转换为大写,其余字符转换为小写。python复制代码
s = "hello, world!"
print(s.capitalize()) # 输出: Hello, world!
-
str.title()
:将字符串中的每个单词的首字母转换为大写,其余字符转换为小写。python复制代码
s = "hello, world!"
print(s.title()) # 输出: Hello, World!
-
str.swapcase()
:将字符串中的大写字符转换为小写,小写字符转换为大写。python复制代码
s = "Hello, World!"
print(s.swapcase()) # 输出: hELLO, wORLD!
-
str.strip([chars])
:移除字符串开头和结尾的空白字符(默认为空格、换行符等),也可以指定要移除的字符。python复制代码
s = " Hello, World! "
print(s.strip()) # 输出: Hello, World!
s = "xxxHello, World!xxx"
print(s.strip('x')) # 输出: Hello, World!
-
str.lstrip([chars])
:移除字符串开头的空白字符(或指定字符)。python复制代码
s = " Hello, World! "
print(s.lstrip()) # 输出: Hello, World!
s = "xxxHello, World!xxx"
print(s.lstrip('x')) # 输出: Hello, World!xxx
-
str.rstrip([chars])
:移除字符串结尾的空白字符(或指定字符)。python复制代码
s = " Hello, World! "
print(s.rstrip()) # 输出: Hello, World!
s = "xxxHello, World!xxx"
print(s.rstrip('x')) # 输出: xxxHello, World!
-
str.split([sep, maxsplit])
:将字符串分割成一个列表,默认按空白字符分割,也可以指定分隔符和最大分割次数。python复制代码
s = "Hello, World, Python!"
print(s.split()) # 输出: ['Hello,', 'World,', 'Python!']
print(s.split(', ')) # 输出: ['Hello', 'World', 'Python!']
print(s.split(',', 1)) # 输出: ['Hello', ' World, Python!']
-
str.rsplit([sep, maxsplit])
:类似于split()
,但分割是从字符串的末尾开始的。python复制代码
s = "Hello, World, Python!"
print(s.rsplit()) # 输出: ['Hello,', 'World,', 'Python!']
print(s.rsplit(', ', 1)) # 输出: ['Hello, World', 'Python!']
-
str.join(iterable)
:将可迭代对象(如列表、元组)中的字符串元素连接成一个新的字符串,元素之间用原字符串作为分隔符。python复制代码
lst = ['Hello', 'World', 'Python']
print(', '.join(lst)) # 输出: Hello, World, Python
-
str.find(sub[, start[, end]])
:返回子字符串sub
在原字符串中最低索引(从左到右),如果未找到则返回 -1。可以指定搜索的起始和结束位置。python复制代码
s = "Hello, World!"
print(s.find('World')) # 输出: 7
print(s.find('Python')) # 输出: -1
-
str.rfind(sub[, start[, end]])
:类似于find()
,但搜索是从右到左的。python复制代码
s = "Hello, Hello, World!"
print(s.rfind('Hello')) # 输出: 13
-
str.index(sub[, start[, end]])
:类似于find()
,但如果未找到子字符串则引发ValueError
异常。python复制代码
s = "Hello, World!"
print(s.index('World')) # 输出: 7
# print(s.index('Python')) # 会引发 ValueError
-
str.rindex(sub[, start[, end]])
:类似于index()
,但搜索是从右到左的。python复制代码
s = "Hello, Hello, World!"
print(s.rindex('Hello')) # 输出: 13
-
str.count(sub[, start[, end]])
:返回子字符串sub
在原字符串中出现的次数,可以指定搜索的起始和结束位置。python复制代码
s = "Hello, Hello, World!"
print(s.count('Hello')) # 输出: 2
-
str.replace(old, new[, count])
:将字符串中的old
子字符串替换为new
,可以指定替换的次数。python复制代码
s = "Hello, Hello, World!"
print(s.replace('Hello', 'Hi')) # 输出: Hi, Hi, World!
print(s.replace('Hello', 'Hi', 1)) # 输出: Hi, Hello, World!
-
str.startswith(prefix[, start[, end]])
:检查字符串是否以指定的前缀开始,可以指定检查的起始和结束位置。python复制代码
s = "Hello, World!"
print(s.startswith('Hello')) # 输出: True
print(s.startswith('World')) # 输出: False
-
str.endswith(suffix[, start[, end]])
:检查字符串是否以指定的后缀结束,可以指定检查的起始和结束位置。python复制代码
s = "Hello, World!"
print(s.endswith('World!')) # 输出: True
print(s.endswith('Hello')) # 输出: False
-
str.isalnum()
:如果字符串中的所有字符都是字母或数字且至少有一个字符,则返回 True,否则返回 False。python复制代码
s = "Hello123"
print(s.isalnum()) # 输出: True
-
str.isalpha()
:如果字符串中的所有字符都是字母且至少有一个字符,则返回 True,否则返回 False。python复制代码
s = "Hello"
print(s.isalpha()) # 输出: True
-
str.isdigit()
:如果字符串中的所有字符都是数字且至少有一个字符,则返回 True,否则返回 False。python复制代码
s = "123"
print(s.isdigit()) # 输出: True
-
str.isspace()
:如果字符串中的所有字符都是空白字符且至少有一个字符,则返回 True,否则返回 False。python复制代码
s = " "
print(s.isspace()) # 输出: True
-
str.istitle()
:如果字符串是标题化的(即每个单词的首字母大写,其余字符小写),则返回 True,否则返回 False。python复制代码
s = "Hello World"
print(s.istitle()) # 输出: True
-
str.zfill(width)
:用零填充字符串的左侧,使其总长度达到指定的宽度。python复制代码
s = "42"
print(s.zfill(5)) # 输出: 00042
-
str.expandtabs(tabsize=8)
:将字符串中的制表符(\t
)替换为指定数量的空格。python复制代码
s = "Hello\tWorld"
print(s.expandtabs(4)) # 输出: Hello World
-
str.format(*args, **kwargs)
:格式化字符串
# 示例 1: 使用位置参数
template = "Hello, {}. You are {} years old."
name = "Alice"
age = 30
formatted_string = template.format(name, age)
print(formatted_string) # 输出: Hello, Alice. You are 30 years old.
# 示例 2: 使用关键字参数
template = "Hello, {name}. You are {age} years old."
formatted_string = template.format(name="Alice", age=30)
print(formatted_string) # 输出: Hello, Alice. You are 30 years old.
# 示例 3: 混合使用位置参数和关键字参数
template = "Hello, {}. My name is {friend_name}. You are {} years old."
formatted_string = template.format("Alice", friend_name="Bob", 30)
# 注意:这种混合方式并不推荐,因为容易引起混淆。
# 更好的方式是全部使用关键字参数来保持清晰。
print(formatted_string) # 输出: Hello, Alice. My name is Bob. You are 30 years old.
# 示例 4: 使用索引和关键字参数
template = "Person {0} is {age1} years old. Person {1} is {age2} years old."
formatted_string = template.format("Alice", "Bob", age1=30, age2=25)
print(formatted_string) # 输出: Person Alice is 30 years old. Person Bob is 25 years old.
# 示例 5: 访问对象属性
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
alice = Person("Alice", 30)
template = "Hello, {0.name}. You are {0.age} years old."
formatted_string = template.format(alice)
print(formatted_string) # 输出: Hello, Alice. You are 30 years old.
# 示例 6: 使用格式化规范
template = "Pi is approximately {:.2f}."
formatted_string = template.format(3.141592653589793)
print(formatted_string) # 输出: Pi is approximately 3.14.
方法总结:
str.capitalize()
- 将字符串的第一个字符转换为大写,其余字符转换为小写。
str.casefold()
- 返回一个字符串,其中所有字符都被转换为小写,用于忽略大小写的字符串比较。
str.center(width[, fillchar])
- 返回一个原字符串居中,并使用指定的填充字符(默认为空格)填充至指定宽度的新字符串。
str.count(sub[, start[, end]])
- 返回子字符串在字符串中出现的次数,可以指定搜索的起始和结束位置。
str.encode(encoding='utf-8', errors='strict')
- 返回字符串的编码版本(字节对象)。
str.endswith(suffix[, start[, end]])
- 判断字符串是否以指定的后缀结束。
str.expandtabs(tabsize=8)
- 将字符串中的制表符(
\t
)转换为指定数量的空格。
- 将字符串中的制表符(
str.find(sub[, start[, end]])
- 返回子字符串在字符串中最低索引(找不到返回-1)。
str.format(*args, **kwargs)
- 格式化字符串,用指定的值替换花括号
{}
中的占位符。
- 格式化字符串,用指定的值替换花括号
str.format_map(mapping)
- 类似于
format()
,但使用字典作为参数。
- 类似于
str.index(sub[, start[, end]])
- 返回子字符串在字符串中最低索引(找不到引发
ValueError
)。
- 返回子字符串在字符串中最低索引(找不到引发
str.isalnum()
- 判断字符串是否只包含字母和数字字符。
str.isalpha()
- 判断字符串是否只包含字母字符。
str.isascii()
- 判断字符串中的所有字符是否都是ASCII字符。
str.isdigit()
- 判断字符串是否只包含数字字符。
str.isdecimal()
- 判断字符串是否只包含十进制数字字符(包括全角字符等)。
str.isidentifier()
- 判断字符串是否是有效的Python标识符。
str.islower()
- 判断字符串中的所有字母是否都是小写。
str.isnumeric()
- 判断字符串是否只包含数字字符(包括全角字符和罗马数字等)。
str.isprintable()
- 判断字符串中的所有字符是否都是可打印的,并且不是控制字符。
str.isspace()
- 判断字符串是否只包含空白字符。
str.istitle()
- 判断字符串是否是标题化的(即每个单词的首字母都是大写)。
str.isupper()
- 判断字符串中的所有字母是否都是大写。
str.join(iterable)
- 将序列中的元素以指定的字符串连接生成一个新的字符串。
str.ljust(width[, fillchar])
- 返回一个原字符串左对齐,并使用指定的填充字符(默认为空格)填充至指定宽度的新字符串。
str.lower()
- 将字符串中的所有字符转换为小写。
str.lstrip([chars])
- 去除字符串左侧的空白字符(或指定的字符)。
str.maketrans(intab, outtab[, transtab])
- 创建字符映射的转换表。通常与
translate()
方法一起使用。
- 创建字符映射的转换表。通常与
str.partition(sep)
- 根据指定的分隔符将字符串分割成三部分,返回一个包含分隔符的元组。
str.replace(old, new[, count])
- 将字符串中的old替换为new,可以指定替换的次数。
str.rfind(sub[, start[, end]])
- 返回子字符串在字符串中最高索引(找不到返回-1)。
str.rindex(sub[, start[, end]])
- 返回子字符串在字符串中最高索引(找不到引发
ValueError
)。
- 返回子字符串在字符串中最高索引(找不到引发
str.rjust(width[, fillchar])
- 返回一个原字符串右对齐,并使用指定的填充字符(默认为空格)填充至指定宽度的新字符串。
str.rpartition(sep)
- 类似于
partition()
,但从字符串的右侧开始分割。
- 类似于
str.rsplit([sep[, maxsplit]])
- 通过指定的分隔符从右侧开始分割字符串,可以指定分割的次数。
str.rstrip([chars])
- 去除字符串右侧的空白字符(或指定的字符)。
str.split([sep[, maxsplit]])
- 通过指定的分隔符将字符串分割成列表,可以指定分割的次数。
str.splitlines([keepends])
- 按照行分隔符将字符串分割成列表,可以保留行尾的分隔符。
str.startswith(prefix[, start[, end]])
- 判断字符串是否以指定的前缀开始。
str.strip([chars])
- 去除字符串前后的空白字符(或指定的字符)。
str.swapcase()
- 反转字符串中的大小写。
str.title()
- 将字符串中的每个单词的首字母转换为大写。
str.translate(table)
- 根据转换表替换字符串中的字符。
str.upper()
- 将字符串中的所有字符转换为大写。
str.zfill(width)
- 在字符串的左侧填充零,直到达到指定的宽度。
这些方法允许你执行各种字符串操作,包括转换、搜索、替换、分割和连接等。