str 类最常用的8个方法
str.lower()
str.upper()
str.split(sep=None, maxsplit=-1)
str.count(sub[, start[, end]])
str.replace(old, new[, count])
str.center(width[, fillchar])
str.strip([chars])
str.join(iterable)
查询方法的文档
根据 成为Python砖家(1): 在本地查询Python HTML文档 提供的方法,在本地查询文档,得到对应函数的说明。
8大方法使用举例
# Python3 str 最常用的8大方法
# author: https://github.com/zchrissirhcz
# ref: https://www.bilibili.com/video/BV1JL4y1x7xC/?p=15
# h1/8
# str.lower() 返回字符串的副本,全部字符为小写
# file:///Users/zz/Documents/python-3.12.5-docs-html/library/stdtypes.html#str.lower
# Return a copy of the string with all the cased characters [4] converted to lowercase.
s = "HELLO WORLD"
t = s.lower()
print(t)
# h2/8
# str.uppper() 返回字符串的副本,全部字符为大写
# file:///Users/zz/Documents/python-3.12.5-docs-html/library/stdtypes.html#str.upper
# Return a copy of the string with all the cased characters [4] converted to uppercase. Note that s.upper().isupper() might be False if s contains uncased characters or if the Unicode category of the resulting character(s) is not “Lu” (Letter, uppercase), but e.g. “Lt” (Letter, titlecase).
u = "hello world"
v = u.upper()
print(v)
print(v.isupper())
# h3/8
# str.split(sep=None, maxsplit=-1) 返回一个列表,由 str 根据 sep 被分割的部分组成
# sep 可以是多个字符, 它们的整体被当作分隔符
# maxsplit表示分隔的数量,默认值-1表示分隔所有的;如果是大于0的取值,那么最多可以得到 maxsplit+1 个元素的 list,最后一个是没有被分割的字符串
# file:///Users/zz/Documents/python-3.12.5-docs-html/library/stdtypes.html#str.split
# Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).
#
# If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters as a single delimiter (to split with multiple delimiters, use re.split()). Splitting an empty string with a specified separator returns [''].
s1 = "The cat sat on the mat, watching the birds through the window while the sun set slowly beyond the horizon."
t1 = s1.split("the")
t2 = s1.split("the", 2)
print("t1", t1)
print("t2", t2)
# h4/8
# str.count(sub[, start[, end]]) 返回字串 sub 在 str 中出现的次数
# file:///Users/zz/Documents/python-3.12.5-docs-html/library/stdtypes.html#str.count
# 可选参数 start 和 end 表示范围,相当于 str[start:end]. 注意,这并不会包含 str[end] 字符
# Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
#
# If sub is empty, returns the number of empty strings between characters which is the length of the string plus one.
s1 = "hello world"
cnt = s1.count('o')
print(f"number of 'o' in '{s1}' = {cnt}")
cnt2 = s1.count('') # 12
print(f"number of '' in '{s1}' = {cnt2}")
cnt3 = s1.count('o', 0, 4)
print(cnt3) # 0
cnt4 = s1.count('o', 0, 5)
print(cnt4) # 1
s2 = "ababab"
cnt5 = s2.count("ab")
print(cnt5) # 3
# h5/8
# str.replace(old, new[, count])
# file:///Users/zz/Documents/python-3.12.5-docs-html/library/stdtypes.html#str.replace
# Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
# 返回字符串 str 的副本, 所有 old 被替换为 new。 如果给了 count 参数,那么只替换前 count 次
s1 = "hello world"
s2 = s1.replace("world", "python")
print(f"s2: {s2}") # hello python
# h6/8
# str.center(width[, fillchar])
# file:///Users/zz/Documents/python-3.12.5-docs-html/library/stdtypes.html#str.center
# Return centered in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).
# 返回字符串 str 根据宽度 width 在左右两侧均等填充 fillchar 后的字符串
# 如果没指定填充字符, 则使用空格填充
# 如果原始字符串长度大于指定的参数 width,那么不填充, 直接返回原始字符串
s1 = "python"
s2 = s1.center(20, "=")
print(s2) # =======python=======
# h7/8
# str.strip([chars])
# file:///Users/zz/Documents/python-3.12.5-docs-html/library/stdtypes.html#str.strip
# Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped.
# 从字符串左右两侧,删除 chars 里出现的字符
# 参数 chars 类型是字符串,但它里面每个字符都被均等对待,任何在 chars 里的字符,都将被剔除
# 如果 chars 参数没指定,则空白字符会被剔除
s1 = "www.example.com"
s2 = s1.strip('comw')
print(s2) # .example.
s3 = "= python= "
s4 = s3.strip(" =np")
print(s4) # "ytho"
# h8/8
# str.join(iterable)
# file:///Users/zz/Documents/python-3.12.5-docs-html/library/stdtypes.html#str.join
# str.join(iterable)
# Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.
# 返回一个字符串,是 iterable 参数中的元素的相互拼接,拼接的粘连符号是 str 本身
s1 = ["1", "2", "3"]
s2 = ','.join(s1)
print(s2) # 1,2,3