python3.12 String类方法大全

字符串相关链接

类型细分与链接注释

字面值

转义字符
字符串字符串基础方法拼接, 索引, 路径, 长字符串分行等等
内置类型str

字符串的方法

见下表

printf 风格的字符串格式化

format % values

标准库string

字符串常量字符串模块中定义的常量
class string.Formatter

自定义字符串格式化

class string.Template(template)

模板字符串

格式字符串语法

str.format()

标准库re

正则表达式语法

模块内容

正则表达式对象 (正则对象)

(常见)正则表达式例子
第三方库regexregex更多功能和Unicode支持
标准库difflibdifflib计算差异的辅助工具
标准库textwarptextwarp文本自动换行与填充

标准库stringprep

stringprep因特网字符串预备

标准库readline

readline

GNU readline 接口

标准库rlcompleter
 
rlcompleterGNU readline 的补全函数

字符串的方法(更新于 2024.7.24)

我感觉比较重要的用红色标出来了

字符串方法(3.12)功能概述(详细内容点击我)
str.capitalize()

【3.8改】返回原字符串的副本,其首个字符大写,其余为小写

print("jASSICA!..".capitalize()) # Jassica!..
print("@".capitalize()) # @
print("ß".capitalize()) # Ss
str.casefold()

【3.3增】返回原字符串消除大小写的副本。 消除大小写的字符串可用于忽略大小写的匹配。

大小写折叠类似于小写,但更具攻击性,因为它旨在删除字符串中的所有大小写区别。例如,德语字母 'ß' 相当于 "ss" 。因为它已经被删除, lower() 不会对 'ß' 做任何事情; casefold() 将其转换为 "ss" 。

print("ß".casefold()) # ss
print("🐲".casefold()) # 🐲
print("ß".lower()) # ß
str.center(width[, fillchar])

返回一个长度为宽度的字符串的中心。填充使用指定的fillchar(默认值为ASCII空格)完成。如果width小于或等于 len(s) ,则返回原始字符串。

print("Chapter One".center(20,'-'))
# ----Chapter One-----
str.count(sub[, start[, end]])

返回子字符串sub在[start,end]范围内非重叠出现的次数。可选参数start和end被解释为切片表示法。

print("*1234*67".count('*'))   # 2
print("*1234*67".count('*',1)) # 1
str.encode(encoding="utf-8"errors="strict")

【3.1 增】【3.9 改】

1. 返回编码为 bytes 的字符串。

2. `errors` 控制如何处理编码错误。如果是 'strict' (默认值),则会引发 UnicodeError 异常。其他可能的值是 'ignore' 、 'replace' 、 'xmlcharrefreplace' 、 'backslashreplace' 和通过 codecs.register_error() 注册的任何其他名称。

3. 出于性能原因,除非实际发生编码错误、启用Python开发模式或使用调试构建,否则不会检查errors值的有效性。

print("abc".encode())  # b'abc'
print("🀄️".encode())   # b'\xf0\x9f\x80\x84\xef\xb8\x8f'
str.endswith(suffix[, start[, end]])

如果字符串以指定的后缀结尾,则返回 True ,否则返回 False 。后缀也可以是要查找的后缀的元组。可选启动时,从该位置开始测试。选择结束,在该位置停止比较。

endings = ('png','jpg','bmp')
print('a.png'.endswith(endings))#True

str.expandtabs(tabsize=8)

返回字符串的副本,其中所有的制表符('\t')会由8个或n个空格替换,具体取决于当前列位置和给定的制表符宽度。

'01\t012\t0123\t01234'.expandtabs()
# '01      012     0123    01234'
'01\t012\t0123\t01234'.expandtabs(4)
# '01  012 0123    01234'
str.find(sub[, start[, end]])

返回子字符串 sub 在 s[start:end] 切片内被找到的最小索引。

注意:只有当你需要知道sub的位置时,才应该使用 find() 方法。要检查sub是否是子串,请使用 in 操作符。

print('Python'.find('Py')) # 0
print('Python'.find('py')) # -1
print('Py' in 'Python')    # True
str.format(*args**kwargs)

执行字符串格式化操作。

详见:string — Common string operations — Python 3.12.4 documentation

print("The sum of 1 + 2 is {0}".format(1+2))
# The sum of 1 + 2 is 3
str.format_map(mapping)

【3.2 增】类似于 str.format(**mapping),不同之处在于 mapping 会被直接使用而不是复制到一个 dict。 

# 定义一个映射,通常是字典
my_map = {
    'name': 'Alice',
    'age': 30
}

# 定义一个格式化的字符串
my_string = "My name is {name} and I am {age} years old."

# 使用format_map方法格式化字符串
formatted_string = my_string.format_map(my_map)

print(formatted_string) # My name is Alice and I am 30 years old.

str.index(sub[, start[, end]])

类似于 find(),但在找不到子类时会引发 ValueError
str.isalnum()如果字符串中的所有字符都是字母数字(alphanumeric),并且至少有一个字符,则返回 True ,否则返回 False 。如果下列之一返回 True ,则字符 c 是字母数字: c.isalpha() 、 c.isdecimal() 、 c.isdigit() 或 c.isnumeric() 。
str.isalpha()如果字符串中的所有字符都是字母,并且至少有一个字符,返回 True ,否则返回 False 。
str.isascii()

【3.7 增】如果字符串为空或字符串中的所有字符都是 ASCII ,返回 True ,否则返回 False 。

print("😮‍💨".isascii()) # False
str.isdecimal()如果字符串中的所有字符都是十进制字符且该字符串至少有一个字符,则返回 True , 否则返回 False 。
str.isdigit()如果字符串中的所有字符都是数字,并且至少有一个字符,返回 True ,否则返回 False 。
str.isidentifier()

如果字符串是有效的标识符,返回 True ,依据语言定义, 标识符和关键字 节。调用 keyword.iskeyword() 来检测字符串 s 是否为保留标识符,例如 def 和 class

# 定义一些字符串
identifiers = ['hello', 'world123', 'Python', '2things', 'my_variable', '__init__', 'class', '42isTheAnswer', '']

# 检查每个字符串是否是有效的标识符
for s in identifiers:
    print(f"'{s}': {s.isidentifier()}")

# 'hello': True
# 'world123': True
# 'Python': True
# '2things': False
# 'my_variable': True
# '__init__': True
# 'class': True
# '42isTheAnswer': False
# '': False

from keyword import iskeyword

'hello'.isidentifier(), iskeyword('hello')
(True, False)
'def'.isidentifier(), iskeyword('def')
(True, True)
str.islower()

如果字符串中至少有一个区分大小写的字符且此类字符均为小写则返回 True ,否则返回 False 。

print("a👌".islower()) # True
str.isnumeric()如果字符串中至少有一个字符且所有字符均为数值字符则返回 True ,否则返回 False 。 
str.isprintable()

如果字符串中的所有字符都是可打印的或字符串为空,则返回 True ,否则返回 False 。不可打印字符是指那些在Unicode字符数据库中定义为“其他”或“分隔符”的字符,但ASCII空格(0x20)除外,它被认为是可打印的。(Note在此上下文中,可打印的字符是当对字符串调用 repr() 时不应转义的字符。它与写入 sys.stdout 或 sys.stderr 的字符串的处理无关。

print("1".isprintable()) # True
print("🤣".isprintable()) # True
print("\t".isprintable()) # False
print("\x1b".isprintable()) # False
str.isspace()如果字符串中只有空白字符且至少有一个字符则返回 True ,否则返回 False 。
str.istitle()

如果字符串中至少有一个字符且为标题字符串则返回 True ,例如大写字符之后只能带非大写字符而小写字符必须有大写字符打头。 否则返回 False 。

# 定义一些字符串
titles = ['Hello World', 'Python Is Great', 'this is not a title', 'Neither is This', 'YES', '']

# 检查每个字符串是否是标题格式
for s in titles:
    print(f"'{s}': {s.istitle()}")

# 'Hello World': True
# 'Python Is Great': True
# 'this is not a title': False
# 'Neither is This': False
# 'YES': False
# '': False
str.isupper()

如果字符串中至少有一个区分大小写的字符且此类字符均为大写则返回 True ,否则返回 False 。

'BANANA'.isupper()
True
'banana'.isupper()
False
'baNana'.isupper()
False
' '.isupper()
False
str.join(iterable)

返回一个由 iterable 中的字符串拼接而成的字符串。 如果 iterable 中存在任何非字符串值包括 bytes 对象则会引发 TypeError。 调用该方法的字符串将作为元素之间的分隔。

print("\t".join(['1','2','3','4']))
# 1       2       3       4
print("\b".join(['1111','222','33','4']))
# 1112234
str.ljust(width[, fillchar])

返回字符串左对齐长度宽度的字符串。填充使用指定的fillchar(默认值为ASCII空格)完成。如果width小于或等于 len(s) ,则返回原始字符串。 

# 定义一个字符串
original_string = "Python"

# 使用ljust方法将字符串左对齐,并填充至长度为10的字符串,默认使用空格填充
left_justified = original_string.ljust(10)

print(f"Left justified (default fill character): '{left_justified}'")
# Left justified (default fill character): 'Python    '

# 使用ljust方法将字符串左对齐,并填充至长度为10的字符串,指定使用星号(*)填充
left_justified_with_star = original_string.ljust(10, '*')

print(f"Left justified with star fill character: '{left_justified_with_star}'")
# Left justified with star fill character: 'Python****'

# 如果指定的长度小于原字符串长度,则返回原字符串
left_justified_short = original_string.ljust(5)

print(f"Left justified with shorter length (no change): '{left_justified_short}'")
# Left justified with shorter length (no change): 'Python'
str.lower()返回原字符串的副本,其所有区分大小写的字符均转换为小写。
str.lstrip([chars])

返回删除前导字符的字符串副本。chars参数是一个字符串,指定要删除的字符集。如果省略或 None ,则chars参数默认为删除空白。chars参数不是前缀;相反,它的值的所有组合都被剥离

'   spacious   '.lstrip()
'spacious   '
'www.example.com'.lstrip('cmowz.')
'example.com'
static str.maketrans(x[, y[, z]])此静态方法返回一个可供 str.translate() 使用的转换对照表。

如果只有一个参数,它必须是一个字典,将Unicode序数(整数)或字符(长度为1的字符串)映射到Unicode序数、字符串(任意长度)或 None 。字符键将被转换为序数。

如果有两个参数,它们必须是长度相等的字符串,在结果字典中,x中的每个字符将映射到y中相同位置的字符。如果有第三个参数,它必须是一个字符串,其字符将映射到结果中的 None 。

# 方法 1 定义一个简单的转换表,将小写字母映射到对应的大写字母
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)

# 方法 2 定义一个字典,将特定的字符映射到其他字符
translation_dict = {
    'a': '1',
    'e': '2',
    'i': '3',
    'o': '4',
    'u': '5'
}
trantab = str.maketrans(translation_dict)

# 定义一个字符串
original_string = "This is an example sentence."

# 使用转换表将字符串中的小写元音字母替换为数字
translated_string = original_string.translate(trantab)

print(f"Original: {original_string}")
# Original: This is an example sentence.
print(f"Translated: {translated_string}")
# Translated: Th3s 3s 1n 2x1mpl2 s2nt2nc2.
str.partition(sep)

在 sep 首次出现的位置拆分字符串,返回一个 3 元组,其中包含分隔符之前的部分、分隔符本身,以及分隔符之后的部分。

# 定义一个字符串
my_string = "Hello, world! This is a test."

# 使用partition方法根据逗号分割字符串
before_comma, comma, after_comma = my_string.partition(',')

# 打印结果
print(f"Before comma: '{before_comma}'")
print(f"Comma: '{comma}'")
print(f"After comma: '{after_comma}'")
# Before comma: 'Hello'
# Comma: ','
# After comma: ' world! This is a test.'

# 如果字符串中没有分隔符,则返回的元组中后两部分将为空字符串
before_dash, dash, after_dash = my_string.partition('-')

# 打印结果
print(f"Before dash: '{before_dash}'")
print(f"Dash: '{dash}'")
print(f"After dash: '{after_dash}'")
# Before dash: 'Hello, world! This is a test.'
# Dash: ''
# After dash: ''
str.removeprefix(prefix/)

【3.9 增】如果字符串以 前缀 字符串开头,返回 string[len(prefix):] 。否则,返回原始字符串的副本。

'TestHook'.removeprefix('Test')
'Hook'
'BaseTestCase'.removeprefix('Test')
'BaseTestCase'
str.removesuffix(suffix/)

【3.9 增】如果字符串以 后缀 字符串结尾,并且 后缀 非空,返回 string[:-len(suffix)] 

'MiscTests'.removesuffix('Tests')
'Misc'
'TmpDirMixin'.removesuffix('Tests')
'TmpDirMixin'
str.replace(oldnew[, count])

返回字符串的副本,其中出现的所有子字符串 old 都将被替换为 new。 如果给出了可选参数 count,则只替换前 count 次出现。

print("1111".replace("1","2",3))#2221
str.rfind(sub[, start[, end]])

返回子字符串 sub 在字符串内被找到的最大(最右)索引,这样 sub 将包含在 s[start:end] 当中。

str.rindex(sub[, start[, end]])类似于 rfind(),但在子字符串 sub 未找到时会引发 ValueError
str.rjust(width[, fillchar])返回长度为 width 的字符串,原字符串在其中靠右对齐。
str.rpartition(sep)在 sep 最后一次出现的位置拆分字符串,返回一个 3 元组,其中包含分隔符之前的部分、分隔符本身,以及分隔符之后的部分。 如果分隔符未找到,则返回的 3 元组中包含两个空字符串以及字符串本身。
str.rsplit(sep=Nonemaxsplit=-1)返回一个由字符串内单词组成的列表,使用 sep 作为分隔字符串。
str.rstrip([chars])

返回删除了尾随字符的字符串副本。chars参数是一个字符串,指定要删除的字符集。如果省略或 None ,则chars参数默认为删除空白。chars参数不是后缀;相反,它的值的所有组合都被剥离

'   spacious   '.rstrip()
'   spacious'
'mississippi'.rstrip('ipz')
'mississ'
str.split(sep=Nonemaxsplit=-1)返回一个由字符串内单词组成的列表,使用 sep 作为分隔字符串。
str.splitlines([keepends])

【3.2 改】返回由原字符串中各行组成的列表,在行边界的位置拆分。 结果列表中不包含行边界,除非给出了 keepends 且为真值。(请参考下边的 Representation & Desciption 表格)

a = '000\n111'
print(a.splitlines()) # ['000', '111']
print(a.splitlines(keepends=True)) # ['000\n', '111']

''.split('\n')
['']
'Two lines\n'.split('\n')
['Two lines', '']
str.startswith(prefix[, start[, end]])如果字符串以指定的 prefix 开始则返回 True,否则返回 False
str.strip([chars])返回原字符串的副本,移除其中的前导和末尾字符。
str.swapcase()返回原字符串的副本,其中大写字符转换为小写,反之亦然。
str.title()

返回原字符串的标题版本,其中每个单词第一个字母为大写,其余字母为小写。

'Hello world'.title()
# 'Hello World'

该算法使用一个简单的独立于语言的单词定义为连续字母组。这个定义适用于许多情况,但它意味着缩写和所有格中的撇号形成了词的边界,这可能不是期望的结果

"they're bill's friends from the UK".title()
# "They'Re Bill'S Friends From The Uk"

可以使用正则表达式构建撇号的解决方案

import re
def titlecase(s):
    return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
                  lambda mo: mo.group(0).capitalize(),
                  s)

titlecase("they're bill's friends.")
"They're Bill's Friends."
str.translate(table)返回原字符串的副本,其中每个字符按给定的转换表进行映射。 转换表必须是一个使用 __getitem__() 来实现索引操作的对象,通常为 mapping 或 sequence
str.upper()返回原字符串的副本,其中所有区分大小写的字符均转换为大写。
str.zfill(width)

返回一个字符串的副本,左填充ASCII '0' 数字,使字符串的长度宽度。前导符号前缀( '+' / '-' )通过在符号字符之后而不是之前插入填充来处理。如果宽度小于或等于 len(s) ,则返回原始字符串。

"42".zfill(5)
'00042'
"-42".zfill(5)
'-0042'

Representation

Description(各种换行)

\n

Line Feed 换行

\r

Carriage Return 回车

\r\n

Carriage Return + Line Feed
回车+换行

\v or \x0b

Line Tabulation 行列表

\f or \x0c

Form Feed 换页

\x1c

File Separator 文件分隔符

\x1d

Group Separator 组分隔符

\x1e

Record Separator 记录分隔符

\x85

Next Line (C1 Control Code)
下一行(C1控制代码)

\u2028

Line Separator 行分隔符

\u2029

Paragraph Separator 段落分隔符

看完了可以考别人的小问题

  1. str.find 和 str.index 有什么区别:index 没找到会报错 find 会返回 -1
  2. find, index, strip, partition, just, 都有从左往右的版本和从右往左的版本
  3. 'mississippi'.rstrip('ipz')返回什么:'mississ',因为会剥离 'ipz'的组合的后缀
  4. str.title, str.upper等等会改变原来的字符串吗:不会,返回的都是字符串副本
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值