目录
str.find() - 检测是否包含指定字符串,可以指定开始和结束位置
str.rfind() - 检测是否包含指定字符串,可以指定开始和结束位置(从右侧开始查询)
str.index() - 与str.find()类似,未找到指定字符串会报异常
str.rindex() - 与str.rfind()类似,未找到指定字符串会报异常
str.count() - 统计指定字符串出现的次数,可以指定开始和结束位置
str.replace() - 替换指定字符串,可以指定替换的数量
str.capitalize() - 把字符串的第一个字符大写,其他的变成小写
str.title() - 把字符串的每个单词首字母大写,其他的改成小写
str.startswith() - 检查字符串是否是以指定字符串开头
str.endswith() - 检查字符串是否以指定字符串结束
str.partition() - 以指定字符串分割成三部分,指定字符串前,指定字符串和指定字符串后
str.rpartition() - 与str.partition()类似,只是从右侧开始
str.splitlines() - 按照行分隔,返回一个包含各行作为元素的列表
str.isalpha() - 如果所有字符都是字母,则返回True,否则返回False
str.isdigit() - 如果所有字符都是数字,则返回True,否则返回False
str.isalnum() - 如果所有字符都是字母或数字,则返回True,否则返回False
str.isspace() - 如果字符串中只包含空格,则返回True,否则返回False
str.join() - 将序列中的元素以指定的字符连接生成一个新的字符串
str.isidentifier() - 判断字符串是否是有效的标识符
str.casefold() - 转换所有字符为小写(不止英文字符)
str.isprintable() - 判断是否所有字符都是可打印的
str.istitle() - 是否每个单词都只有首字母大写, 其余字母小写
str.encode() - 以指定的编码格式编码字符串,默认为"utf-8"
str.decode() - 以指定的编码格式解码字符串,默认为"utf-8"
str.removeprefix() - 删除开头指定字符串
str.removesuffix() - 删除结尾指定字符串
str.translate() - 根据参数 table 给出的表(包含 256 个字符)转换字符串的字符
str.center() - 字符串居中
与第一篇介绍的格式化中的居中效果类似。
'''
center(width, fillchar=' ') method of builtins.str instance
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
'''
s1 = "Example"
# 使用center()函数
print(s1.center(11)) # Example
print(s1.center(11, "*")) # **Example**
# 使用^进行格式化
print(f"{s1:^11}") # Example
print(f"{s1:*^11}") # **Example**
str.ljust() - 字符串居左
与第一篇介绍的<居左格式化效果类似
'''
ljust(width, fillchar=' ') method of builtins.str instance
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
'''
s1 = "Example"
# 使用ljust()函数
print(s1.ljust(11)) # Example
print(s1.ljust(11), "*") # Example****
# 使用<进行格式化
print(f"{s1:<11}") # Example
print(f"{s1:*<11}") # Example****
str.rjust() - 字符串居右
与第一篇介绍的>居左格式化效果类似
'''
rjust(width, fillchar=' ', /) method of builtins.str instance
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
'''
s1 = "Example"
# 使用rjust()函数
print(s1.rjust(11)) # Example
print(s1.rjust(11, "*")) # ****Example
# 使用<进行格式化
print(f"{s1:>11}") # Example
print(f"{s1:*>11}") # ****Example
str.lstrip() - 去掉左边空格或指定字符串
'''
strip(chars=None) method of builtins.str instance
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
'''
s2 = " Example "
# 默认去掉左边空格
print(s2.lstrip()) # Example
s3 = "eeExampleee"
# 去掉左边的e
print(s3.lstrip("e")) # Exampleee
str.rstrip() - 去掉右边空格或指定字符串
'''
rstrip(chars=None) method of builtins.str instance
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
'''
s2 = " Example "
# 去掉右边空格
print(s2.rstrip()) # Example
s3 = "eeExampleee"
# 去掉右边的e
print(s3.rstrip("e")) # eeExampl
str.strip() - 去掉两边空格或指定字符串
'''
strip(chars=None) method of builtins.str instance
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
'''
s2 = " Example "
# 去掉两边的空格
print(s2.strip()) # Example
s3 = "eeExampleee"
# 去掉两边的e
print(s3.strip("e")) # Exampl
str.find() - 检测是否包含指定字符串,可以指定开始和结束位置
从左侧开始查询,找到第一个指定字符串则返回索引位置,否则返回-1
'''
find(...) method of builtins.str instance
S.find(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
'''
s4 = "hello world"
# 查询是否包含子字符串
print(s4.find("o")) # 4
# 没有找到子字符串则返回-1
print(s4.find("s")) # -1
# 指定开始位置
print(s4.find("o", 5)) # 7
# 指定开始和结束位置
print(s4.find("o", 5, 6)) # -1
str.rfind() - 检测是否包含指定字符串,可以指定开始和结束位置(从右侧开始查询)
与find()类似,不过是从右侧开始
'''
rfind(...) method of builtins.str instance
S.rfind(sub[, start[, end]]) -> int
Return the highest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
'''
s4 = "hello world"
print(s4.rfind("o")) # 7
str.index() - 与str.find()类似,未找到指定字符串会报异常
'''
index(...) method of builtins.str instance
S.index(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
'''
s4 = "hello world"
# 找到包含的字符串则返回索引位置
print(s4.index("o")) # 4
# 不包含指定的字符串则报错
print(s4.index("s")) # ValueError: substring not found
str.rindex() - 与str.rfind()类似,未找到指定字符串会报异常
'''
rindex(...) method of builtins.str instance
S.rindex(sub[, start[, end]]) -> int
Return the highest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
'''
s4 = "hello world"
# 找到包含的字符串则返回索引位置
print(s4.rindex("o")) # 4
# 不包含指定的字符串则报错
print(s4.rindex("s")) # ValueError: substring not found
str.count() - 统计指定字符串出现的次数,可以指定开始和结束位置
'''
count(...) method of builtins.str instance
S.count(sub[, start[, end]]) -> int
Return the number of non-overlapping occurrences of substring sub in
string S[start:end]. Optional arguments start and end are
interpreted as in slice notation.
'''
s4 = "hello word"
# 统计字符串出现的次数
print(s4.count("o")) # 2
# 指定开始位置
print(s4.count("o", 5)) # 1
# 指定开始和结束位置
print(s4.count("o", 5, 6)) # 0
str.replace() - 替换指定字符串,可以指定替换的数量
<count>表示替换的最大次数,默认是-1
'''
replace(old, new, count=-1) method of builtins.str instance
Return a copy with all occurrences of substring old replaced by new.
count
Maximum number of occurrences to replace.
-1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are
replaced.
'''
s4 = "hello world"
# 将所有o替换成oo
print(s4.replace("o", "oo")) # helloo woorld
# 指定最多替换1次
print(s4.replace("o", "oo", 1)) # helloo world
str.split() - 以指定字符串为分隔符进行切片
'''
split(sep=None, maxsplit=-1) method of builtins.str instance
Return a list of the words in the string, using sep as the delimiter string.
sep
The delimiter according which to split the string.
None (the default value) means split according to any whitespace,
and discard empty strings from the result.
maxsplit
Maximum number of splits to do.
-1 (the default value) means no limit.
'''
s4 = "hello world"
print(s4.split("l")) # ['he', '', 'o wor', 'd']
# 限定分割次数
print(s4.split("l", 1)) # ['he', '', 'o world']
str.capitalize() - 把字符串的第一个字符大写,其他的变成小写
'''
capitalize() method of builtins.str instance
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower
case.
'''
s4 = "hello world"
print(s4.capitalize()) # Hello world
str.title() - 把字符串的每个单词首字母大写,其他的改成小写
'''
title() method of builtins.str instance
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining
cased characters have lower case.
'''
s4 = "hello world"
print(s4.title()) # Hello World
str.startswith() - 检查字符串是否是以指定字符串开头
'''
startswith(...) method of builtins.str instance
S.startswith(prefix[, start[, end]]) -> bool
Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.
'''
s4 = "hello word"
print(s4.startswith("h")) # True
print(s4.startswith("w")) # False
str.endswith() - 检查字符串是否以指定字符串结束
'''
endswith(...) method of builtins.str instance
S.endswith(suffix[, start[, end]]) -> bool
Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try.
'''
s4 = "hello word"
print(s4.endswith("d")) # True
print(s4.endswith("o")) # False
# 指定开始位置
print(s4.endswith("d", 4)) # True
# 指定开始和结束位置
print(s4.endswith("o", 1, 5)) # True
str.lower() - 转换所有大写字符为小写
'''
lower() method of builtins.str instance
Return a copy of the string converted to lowercase.
'''
s5 = "HELLO WORLD"
print(s5.lower()) # hello world
str.upper() - 转换所有小写字母为大写
'''
upper() method of builtins.str instance
Return a copy of the string converted to uppercase.
'''
s4 = "hello world"
print(s4.upper()) # HELLO WORLD
str.partition() - 以指定字符串分割成三部分,指定字符串前,指定字符串和指定字符串后
'''
partition(sep) method of builtins.str instance
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found,
returns a 3-tuple containing the part before the separator, the separator
itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string
and two empty strings.
'''
s4 = "hello world"
print(s4.partition("o")) # ('hell', 'o', ' world')
str.rpartition() - 与str.partition()类似,只是从右侧开始
'''
rpartition(sep) method of builtins.str instance
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If
the separator is found, returns a 3-tuple containing the part before the
separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings
and the original string.
'''
s4 = "hello world"
print(s4.rpartition("o")) # ('hello w', 'o', 'rld')
str.splitlines() - 按照行分隔,返回一个包含各行作为元素的列表
'''
rpartition(sep) method of builtins.str instance
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If
the separator is found, returns a 3-tuple containing the part before the
separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings
and the original string.
'''
s6 = "Hello World!\n I'm Max!"
print(s6.splitlines()) # ['Hello World!', " I'm Max!"]
str.isalpha() - 如果所有字符都是字母,则返回True,否则返回False
'''
isalpha() method of builtins.str instance
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there
is at least one character in the string.
'''
s7 = "hello"
print(s7.isalpha()) # True
str.isdigit() - 如果所有字符都是数字,则返回True,否则返回False
'''
isdigit() method of builtins.str instance
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there
is at least one character in the string.
'''
s8 = "4567124"
print(s8.isdigit()) # True
str.isalnum() - 如果所有字符都是字母或数字,则返回True,否则返回False
'''
isdigit() method of builtins.str instance
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there
is at least one character in the string.
'''
s9 = "test123"
print(s8.isdigit()) # True
str.isspace() - 如果字符串中只包含空格,则返回True,否则返回False
'''
isspace() method of builtins.str instance
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there
is at least one character in the string.
'''
s10 = " "
print(s10.isspace()) # True
str.join() - 将序列中的元素以指定的字符连接生成一个新的字符串
'''
join(iterable, /) method of builtins.str instance
Concatenate any number of strings.
The string whose method is called is inserted in between each given string.
The result is returned as a new string.
Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs
'''
print("-".join(["hello", "word"])) # hello-word
str.isidentifier() - 判断字符串是否是有效的标识符
'''
isidentifier() method of builtins.str instance
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
such as "def" or "class".
'''
print("hello".isidentifier()) # True
str.casefold() - 转换所有字符为小写(不止英文字符)
'''
casefold() method of builtins.str instance
Return a version of the string suitable for caseless comparisons.
'''
s11 = "Δ"
print(s11.casefold()) # δ
str.swapcase() - 大小写切换
'''
swapcase() method of builtins.str instance
Convert uppercase characters to lowercase and lowercase characters to uppercase.
'''
s12 = "Test String"
print(s12.swapcase()) # tEST sTRING
str.isprintable() - 判断是否所有字符都是可打印的
'''
isprintable() method of builtins.str instance
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in
repr() or if it is empty.
'''
s12 = "Test String"
s13 = "Hello world\n"
print(s12.isprintable()) # True
print(s13.isprintable()) # False
str.istitle() - 是否每个单词都只有首字母大写, 其余字母小写
'''
istitle() method of builtins.str instance
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only
follow uncased characters and lowercase characters only cased ones.
'''
s14 = "Hello world"
s15 = "hello world"
s16 = "Hello World"
print(s14.istitle()) # False
print(s15.istitle()) # False
print(s16.istitle()) # True
str.encode() - 以指定的编码格式编码字符串,默认为"utf-8"
'''
encode(encoding='utf-8', errors='strict') method of builtins.str instance
Encode the string using the codec registered for encoding.
encoding
The encoding in which to encode the string.
errors
The error handling scheme to use for encoding errors.
The default is 'strict' meaning that encoding errors raise a
UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
'xmlcharrefreplace' as well as any other name registered with
codecs.register_error that can handle UnicodeEncodeErrors.
'''
s17 = "天气"
print(s17.encode()) # b'\xe5\xa4\xa9\xe6\xb0\x94'
str.decode() - 以指定的编码格式解码字符串,默认为"utf-8"
'''
decode(encoding='utf-8', errors='strict') method of builtins.bytes instance
Decode the bytes using the codec registered for encoding.
encoding
The encoding with which to decode the bytes.
errors
The error handling scheme to use for the handling of decoding errors.
The default is 'strict' meaning that decoding errors raise a
UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
as well as any other name registered with codecs.register_error that
can handle UnicodeDecodeErrors.
'''
s18 = b"aabbcc"
print(s18.decode()) # aabbcc
str.removeprefix() - 删除开头指定字符串
'''
removeprefix(prefix, /) method of builtins.str instance
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):].
Otherwise, return a copy of the original string.
'''
s19 = "abcdefg"
print(s19.removeprefix("ab")) # cdefg
str.removesuffix() - 删除结尾指定字符串
'''
removesuffix(suffix, /) method of builtins.str instance
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty,
return string[:-len(suffix)]. Otherwise, return a copy of the original
string.
'''
s19 = "abcdefg"
print(s19.removesuffix("fg")) # abcde
str.zfill() - 用0按指定长度填充字符串
'''
zfill(width, /) method of builtins.str instance
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
'''
s19 = "abcdefg"
print(s19.zfill(20)) # 0000000000000abcdefg
str.translate() - 根据参数 table 给出的表(包含 256 个字符)转换字符串的字符
'''
translate(table) method of builtins.str instance
Replace each character in the string using the given translation table.
table
Translation table, which must be a mapping of Unicode ordinals to
Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a
dictionary or list. If this operation raises LookupError, the character is
left untouched. Characters mapped to None are deleted.
'''
a = "abcdefgh"
print(a.translate({ord("a"):"Xis", ord("b"):"ZYh"})) # XisZYhcdefgh
# table也可以用maketrans生成
table = str.maketrans("ac", "yx")
print(a.translate(table)) # ybxdefgh
str.expandtabs() - 将\t转换为空格
'''
expandtabs(tabsize=8) method of builtins.str instance
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
'''
s20 = "Go\t home"
print(s20.expandtabs(4)) # Go home