目录
一、字符串
1、字符串的定义
在Python中,字符串(Str)是一种数据类型,用于存储一系列字符(文本),字符串可以包含字母、数字、标点符号和特殊字符等。
在Python中,可以通过以下几种方式定义字符串:
1-1、使用单引号(')
- s1 = 'Hello, my Python World!'
- print(type(s1)) # 输出:
1-2、使用双引号(")
- s1 = "Hello, my Python World!"
- print(type(s1)) # 输出:
1-3、使用三引号('''或""")
- # 使用三个单引号:'''
- s1 = '''Hello, my Python World!'''
- print(type(s1)) # 输出:
- # 使用三个双引号:"""
- s1 = """Hello, my Python World!"""
- print(type(s1)) # 输出:
1-4、原始字符串(r'str'或R'str')
- # 用r'str'
- path1 = r'C:\Users\Username\Documents\file.txt'
- print(type(path1)) # 输出:
- # 用r"str"
- path2 = r"C:\Users\Username\Documents\file.txt"
- print(type(path2)) # 输出:
- # 用r'''str'''
- path3 = r'''C:\Users\Username\Documents\file.txt'''
- print(type(path3)) # 输出:
- # 用r"""str"""
- path4 = r"""C:\Users\Username\Documents\file.txt"""
- print(type(path4)) # 输出:
- # 用R'str'
- path5 = R'C:\Users\Username\Documents\file.txt'
- print(type(path5)) # 输出:
- # 用R"str"
- path6 = R"C:\Users\Username\Documents\file.txt"
- print(type(path6)) # 输出:
- # 用R'''str'''
- path7 = R'''C:\Users\Username\Documents\file.txt'''
- print(type(path7)) # 输出:
- # 用R"""str"""
- path8 = R"""C:\Users\Username\Documents\file.txt"""
- print(type(path8)) # 输出:
2、字符串的语法
Python中的字符串是由单引号(')、双引号(")或三引号(''' 或 """)括起来的字符或文本,字符串可以是ASCII字符、Unicode字符或两者都有。
3、获取字符串的属性和方法
用dir()函数获取str所有属性和方法的列表
- print(dir(str))
- # ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
- # '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__',
- # '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
- # '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold',
- # 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha',
- # 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper',
- # 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex',
- # 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
4、获取字符串的帮助信息
用help()函数获取str的帮助信息
- Help on class str in module builtins:
-
- class str(object)
- | str(object='') -> str
- | str(bytes_or_buffer[, encoding[, errors]]) -> str
- |
- | Create a new string object from the given object. If encoding or
- | errors is specified, then the object must expose a data buffer
- | that will be decoded using the given encoding and error handler.
- | Otherwise, returns the result of object.__str__() (if defined)
- | or repr(object).
- | encoding defaults to sys.getdefaultencoding().
- | errors defaults to 'strict'.
- |
- | Methods defined here:
- |
- | __add__(self, value, /)
- | Return self+value.
- |
- | __contains__(self, key, /)
- | Return key in self.
- |
- | __eq__(self, value, /)
- | Return self==value.
- |
- | __format__(self, format_spec, /)
- | Return a formatted version of the string as described by format_spec.
- |
- | __ge__(self, value, /)
- | Return self>=value.
- |
- | __getattribute__(self, name, /)
- | Return getattr(self, name).
- |
- | __getitem__(self, key, /)
- | Return self[key].
- |
- | __getnewargs__(...)
- |
- | __gt__(self, value, /)
- | Return self>value.
- |
- | __hash__(self, /)
- | Return hash(self).
- |
- | __iter__(self, /)
- | Implement iter(self).
- |
- | __le__(self, value, /)
- | Return self<=value.
- |
- | __len__(self, /)
- | Return len(self).
- |
- | __lt__(self, value, /)
- | Return self
- |
- | __mod__(self, value, /)
- | Return self%value.
- |
- | __mul__(self, value, /)
- | Return self*value.
- |
- | __ne__(self, value, /)
- | Return self!=value.
- |
- | __repr__(self, /)
- | Return repr(self).
- |
- | __rmod__(self, value, /)
- | Return value%self.
- |
- | __rmul__(self, value, /)
- | Return value*self.
- |
- | __sizeof__(self, /)
- | Return the size of the string in memory, in bytes.
- |
- | __str__(self, /)
- | Return str(self).
- |
- | capitalize(self, /)
- | Return a capitalized version of the string.
- |
- | More specifically, make the first character have upper case and the rest lower
- | case.
- |
- | casefold(self, /)
- | Return a version of the string suitable for caseless comparisons.
- |
- | center(self, width, fillchar=' ', /)
- | Return a centered string of length width.
- |
- | Padding is done using the specified fill character (default is a space).
- |
- | count(...)
- | 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.
- |
- | encode(self, /, encoding='utf-8', errors='strict')
- | 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.
- |
- | endswith(...)
- | 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.
- |
- | expandtabs(self, /, tabsize=8)
- | Return a copy where all tab characters are expanded using spaces.
- |
- | If tabsize is not given, a tab size of 8 characters is assumed.
- |
- | find(...)
- | 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.
- |
- | format(...)
- | S.format(*args, **kwargs) -> str
- |
- | Return a formatted version of S, using substitutions from args and kwargs.
- | The substitutions are identified by braces ('{' and '}').
- |
- | format_map(...)
- | S.format_map(mapping) -> str
- |
- | Return a formatted version of S, using substitutions from mapping.
- | The substitutions are identified by braces ('{' and '}').
- |
- | index(...)
- | 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.
- |
- | isalnum(self, /)
- | Return True if the string is an alpha-numeric string, False otherwise.
- |
- | A string is alpha-numeric if all characters in the string are alpha-numeric and
- | there is at least one character in the string.
- |
- | isalpha(self, /)
- | 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.
- |
- | isascii(self, /)
- | Return True if all characters in the string are ASCII, False otherwise.
- |
- | ASCII characters have code points in the range U+0000-U+007F.
- | Empty string is ASCII too.
- |
- | isdecimal(self, /)
- | Return True if the string is a decimal string, False otherwise.
- |
- | A string is a decimal string if all characters in the string are decimal and
- | there is at least one character in the string.
- |
- | isdigit(self, /)
- | 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.
- |
- | isidentifier(self, /)
- | 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".
- |
- | islower(self, /)
- | Return True if the string is a lowercase string, False otherwise.
- |
- | A string is lowercase if all cased characters in the string are lowercase and
- | there is at least one cased character in the string.
- |
- | isnumeric(self, /)
- | Return True if the string is a numeric string, False otherwise.
- |
- | A string is numeric if all characters in the string are numeric and there is at
- | least one character in the string.
- |
- | isprintable(self, /)
- | 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.
- |
- | isspace(self, /)
- | 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.
- |
- | istitle(self, /)
- | 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.
- |
- | isupper(self, /)
- | Return True if the string is an uppercase string, False otherwise.
- |
- | A string is uppercase if all cased characters in the string are uppercase and
- | there is at least one cased character in the string.
- |
- | join(self, iterable, /)
- | 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'
- |
- | ljust(self, width, fillchar=' ', /)
- | Return a left-justified string of length width.
- |
- | Padding is done using the specified fill character (default is a space).
- |
- | lower(self, /)
- | Return a copy of the string converted to lowercase.
- |
- | lstrip(self, chars=None, /)
- | Return a copy of the string with leading whitespace removed.
- |
- | If chars is given and not None, remove characters in chars instead.
- |
- | partition(self, sep, /)
- | 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.
- |
- | removeprefix(self, prefix, /)
- | 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.
- |
- | removesuffix(self, suffix, /)
- | 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.
- |
- | replace(self, old, new, count=-1, /)
- | 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.
- |
- | rfind(...)
- | 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.
- |
- | rindex(...)
- | 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.
- |
- | rjust(self, width, fillchar=' ', /)
- | Return a right-justified string of length width.
- |
- | Padding is done using the specified fill character (default is a space).
- |
- | rpartition(self, sep, /)
- | 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.
- |
- | rsplit(self, /, sep=None, maxsplit=-1)
- | Return a list of the substrings in the string, using sep as the separator string.
- |
- | sep
- | The separator used to split the string.
- |
- | When set to None (the default value), will split on any whitespace
- | character (including \n \r \t \f and spaces) and will discard
- | empty strings from the result.
- | maxsplit
- | Maximum number of splits.
- | -1 (the default value) means no limit.
- |
- | Splitting starts at the end of the string and works to the front.
- |
- | rstrip(self, chars=None, /)
- | Return a copy of the string with trailing whitespace removed.
- |
- | If chars is given and not None, remove characters in chars instead.
- |
- | split(self, /, sep=None, maxsplit=-1)
- | Return a list of the substrings in the string, using sep as the separator string.
- |
- | sep
- | The separator used to split the string.
- |
- | When set to None (the default value), will split on any whitespace
- | character (including \n \r \t \f and spaces) and will discard
- | empty strings from the result.
- | maxsplit
- | Maximum number of splits.
- | -1 (the default value) means no limit.
- |
- | Splitting starts at the front of the string and works to the end.
- |
- | Note, str.split() is mainly useful for data that has been intentionally
- | delimited. With natural text that includes punctuation, consider using
- | the regular expression module.
- |
- | splitlines(self, /, keepends=False)
- | Return a list of the lines in the string, breaking at line boundaries.
- |
- | Line breaks are not included in the resulting list unless keepends is given and
- | true.
- |
- | startswith(...)
- | 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.
- |
- | strip(self, chars=None, /)
- | Return a copy of the string with leading and trailing whitespace removed.
- |
- | If chars is given and not None, remove characters in chars instead.
- |
- | swapcase(self, /)
- | Convert uppercase characters to lowercase and lowercase characters to uppercase.
- |
- | title(self, /)
- | 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.
- |
- | translate(self, table, /)
- | 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.
- |
- | upper(self, /)
- | Return a copy of the string converted to uppercase.
- |
- | zfill(self, width, /)
- | Pad a numeric string with zeros on the left, to fill a field of the given width.
- |
- | The string is never truncated.
- |
- | ----------------------------------------------------------------------
- | Static methods defined here:
- |
- | __new__(*args, **kwargs) from builtins.type
- | Create and return a new object. See help(type) for accurate signature.
- |
- | maketrans(...)
- | Return a translation table usable for str.translate().
- |
- | If there is only one argument, it must be a dictionary mapping Unicode
- | ordinals (integers) or characters to Unicode ordinals, strings or None.
- | Character keys will be then converted to ordinals.
- | If there are two arguments, they must be strings of equal length, and
- | in the resulting dictionary, each character in x will be mapped to the
- | character at the same position in y. If there is a third argument, it
- | must be a string, whose characters will be mapped to None in the result.
5、字符串的用法
5-31、rfind()方法
- # 1、方法:str.rfind
- # 2、语法:str.rfind(sub[, start[, end]])
- # 3、参数:
- # 3-1、sub(必须):需要被查找的子串
- # 3-2、start(可选):开始搜索的索引位置;默认为 -1,表示从字符串的末尾开始搜索
- # 3-3、end(可选):结束搜索的索引位置(不包括);默认为字符串的长度
- # 4、功能:用于从字符串的末尾开始查找指定的子串,并返回该子串最后出现的位置的索引;如果未找到该子串,则返回-1
- # 5、返回值:返回被查找子串最后出现位置的索引
- # 6、说明:
- # 6-1、与find()方法类似,但rfind()是从字符串的末尾开始搜索
- # 6-2、start和end参数都可以是负数,表示从字符串的末尾开始计算索引
- # 7、示例:
- # 示例1:查找子串最后出现的位置
- s = "Hello, world! Hello everyone."
- index = s.rfind("Hello")
- print(index) # 输出: 14,因为 "Hello" 最后一次出现在索引14的位置
- # 示例2:使用可选参数 start 和 end
- s = "apple, banana, apple pie"
- index = s.rfind("apple", 0, 10) # 从索引0开始,到索引10(不包括)结束搜索
- print(index) # 输出: 0,因为在这个范围内,"apple" 第一次(也是唯一一次)出现在索引0的位置
- # 示例3:未找到子串时返回 -1
- s = "banana, banana split"
- index = s.rfind("apple")
- print(index) # 输出: -1,因为 "apple" 没有出现在字符串中
- # 示例4:使用 start 的默认值从字符串末尾开始搜索
- s = "abcabcabc"
- index = s.rfind("abc", -4) # 从索引-4(即倒数第四个字符)开始搜索,这等同于从末尾开始搜索
- print(index) # 输出: 6,因为 "abc" 最后一次出现在索引6的位置
5-32、rindex()方法
- # 1、方法:str.rindex
- # 2、语法:str.rindex(sub[, start[, end]])
- # 3、参数:
- # 3-1、sub(必须):需要被查找的子串
- # 3-2、start(可选):开始搜索的索引位置;默认为 -1,表示从字符串的末尾开始搜索
- # 3-3、end(可选):结束搜索的索引位置(不包括);默认为字符串的长度
- # 4、功能:用于从字符串的末尾开始查找指定的子串,并返回该子串最后出现的位置的索引;如果未找到该子串,则会引发ValueError异常
- # 5、返回值:返回被查找子串最后出现位置的索引
- # 6、说明:
- # 6-1、如果子串sub存在于字符串中,rindex()会返回子串最后出现的位置的索引;如果未找到子串,则会引发ValueError异常
- # 7、示例:
- # 示例1:查找子串最后出现的位置
- s = "Hello, world! Hello everyone."
- index = s.rindex("Hello")
- print(index) # 输出: 14,因为"Hello"最后一次出现在索引14的位置
- # 示例2:使用可选参数start和end
- s = "apple, banana, apple pie"
- index = s.rindex("apple", 0, 13) # 从索引0开始,到索引13(不包括)结束搜索
- print(index) # 输出: 0,因为在这个范围内,"apple" 第一次(也是唯一一次)出现在索引0的位置
- # 示例3:未找到子串时引发 ValueError 异常
- s = "banana, banana split"
- try:
- index = s.rindex("apple")
- print(index) # 这行代码不会执行,因为会抛出异常
- except ValueError:
- print("子串未找到") # 输出: 子串未找到
- # 示例4:使用 start 的默认值从字符串末尾开始搜索
- s = "abcabcabc"
- index = s.rindex("abc", -4) # 从索引-4(即倒数第四个字符)开始搜索,这等同于从末尾开始搜索
- print(index) # 输出: 6,因为 "abc" 最后一次出现在索引6的位置
5-33、rjust()方法
- # 1、方法:str.rjust
- # 2、语法:str.rjust(width[, fillchar])
- # 3、参数:
- # 3-1、width:所需的最小宽度;如果指定了负值,则会引发ValueError
- # 3-2、fillchar(可选):用于填充的字符;默认为空格字符(' ')
- # 4、功能:用于在字符串的左侧填充指定的字符,直到达到指定的总长度
- # 5、返回值:一个指定长度的新字符串
- # 6、说明:
- # 7、示例:
- # 示例1:填充空格至指定宽度
- s = "hello"
- s_padded = s.rjust(10)
- print(s_padded) # 输出: ' hello'(左侧填充了5个空格)
- # 示例2:使用指定的填充字符
- s = "42"
- s_padded = s.rjust(5, '0')
- print(s_padded) # 输出: '00042'(左侧填充了3个'0')
- # 示例3:如果字符串已经达到或超过指定宽度,则原样返回
- s = "superlongstring"
- s_padded = s.rjust(10)
- print(s_padded) # 输出: 'superlongstring'(没有填充,因为原字符串已经超过了指定宽度)
5-34、rpartition()方法
- # 1、方法:str.rpartition
- # 2、语法:str.rpartition(sep)
- # 3、参数:
- # 3-1、sep:用于分割字符串的分隔符
- # 4、功能:用于从右边开始搜索分隔符,将字符串分割为三部分,返回一个包含三个元素的元组,这三个元素分别是:分隔符之前的子串、分隔符本身以及分隔符之后的子串
- # 5、返回值:返回包含三部分(分隔符之前的部分、分隔符本身和分隔符之后的部分)的元组
- # 6、说明:
- # 7、示例:
- # 示例1:使用分隔符进行分割
- s = "www.example.com"
- parts = s.rpartition(".")
- print(parts) # 输出: ('www.example', '.', 'com')
- # 示例2:如果分隔符不存在于字符串中
- s = "no_dots_here"
- parts = s.rpartition(".")
- print(parts) # 输出: ('no_dots_here', '', '')
- # 示例3:分隔符是字符串的一部分但不是分隔符
- s = "hello.world.example"
- parts = s.rpartition(".")
- print(parts) # 输出: ('hello.world', '.', 'example')
- # 注意这里是从右侧开始搜索,所以只找到了最右侧的"."
5-35、rsplit()方法
- # 1、方法:str.rsplit
- # 2、语法:str.rsplit(sep=None, maxsplit=-1)
- # 3、参数:
- # 3-1、sep:用于分割字符串的分隔符;默认为所有的空字符,包括空格、换行符、制表符等,如果指定了分隔符,则只会在该分隔符处进行分割
- # 3-2、maxsplit:分割的最大次数;默认为 -1,表示分割所有可能的子串,如果指定了maxsplit,则分割会在达到maxsplit次后停止,即使字符串中还存在分隔符
- # 4、功能:用于从字符串的右侧开始分割字符串。这个方法会根据指定的分隔符(sep)和最大分割次数(maxsplit,可选参数)将字符串分割为多个子串,并返回一个列表
- # 5、返回值:一个列表
- # 6、说明:
- # 6-1、如果sep不存在于字符串中,或者maxsplit设置为0或负数(且小于-1),则整个字符串将作为一个单独的子串返回
- # 6-2、如果未指定sep,则默认使用所有的空字符作为分隔符,包括但不限于包括空格、换行符、制表符等
- # 7、示例:
- # 示例1:使用空格作为分隔符
- s = "one two three four"
- parts = s.rsplit()
- print(parts) # 输出: ['one', 'two', 'three', 'four']
- # 示例2:指定分隔符和最大分割次数
- s = "a-b-c-d-e"
- parts = s.rsplit("-", 2)
- print(parts) # 输出: ['a-b-c', 'd', 'e']
- # 示例3:只指定分隔符
- s = "a,b,c,d,e"
- parts = s.rsplit(",")
- print(parts) # 输出: ['a', 'b', 'c', 'd', 'e']
- # 示例4:指定不存在的分隔符
- s = "no_dashes_here"
- parts = s.rsplit("-")
- print(parts) # 输出: ['no_dashes_here']
- # 示例5:指定分隔符和maxsplit=1
- s = "a,b,c,d,e"
- parts = s.rsplit(",", 1)
- print(parts) # 输出: ['a,b,c,d', 'e']
5-36、rstrip()方法
- # 1、方法:str.rstrip
- # 2、语法:str.rstrip([chars])
- # 3、参数:
- # 3-1、chars(可选):一个字符串,指定要从原始字符串的右侧删除的字符集合;如果省略或未指定,则默认删除所有尾随的空白字符
- # 4、功能:用于从字符串的右侧(末尾)删除指定的字符(或字符集合);默认情况下,它会删除所有尾随的空白字符(包括空格、换行符、制表符等)
- # 5、返回值:一个新的字符串,它是原始字符串的副本,但右侧不再包含指定的字符
- # 6、说明:
- # 6-1、如果未指定chars,则默认删除所有尾随的空白字符,返回的是处理后的新字符串,而原始字符串保持不变
- # 7、示例:
- # 示例1:删除尾随的空白字符
- s = " Hello, World! "
- s_stripped = s.rstrip()
- print(s_stripped) # 输出: " Hello, World!"(注意右侧的空格被删除了)
- # 示例2:删除尾随的指定字符
- s = "Hello, World!!!"
- s_stripped = s.rstrip("!")
- print(s_stripped) # 输出: "Hello, World"(注意尾随的"!"被删除了)
- # 示例3:删除尾随的多个字符
- s = "apples, oranges, and bananas,,,"
- s_stripped = s.rstrip(", ")
- print(s_stripped) # 输出: "apples, oranges, and bananas"(注意尾随的逗号和空格被删除了)
- # 示例4:如果指定字符不存在于末尾,则原样返回
- s = "Hello, World"
- s_stripped = s.rstrip("!")
- print(s_stripped) # 输出: "Hello, World"(字符串未改变,因为没有尾随的"!")
5-37、split()方法
- # 1、方法:str.split
- # 2、语法:str.split(sep=None, maxsplit=-1)
- # 3、参数:
- # 3-1、sep(可选):用于分割字符串的分隔符;默认为None,表示在任意空白处分割
- # 3-2、maxsplit(可选):分割的最大次数;默认为-1,表示分割所有可能的子串,如果指定了maxsplit,则分割会在达到maxsplit次后停止,即使字符串中还存在分隔符
- # 4、功能:用于将字符串分割成子字符串列表,分割基于指定的分隔符
- # 5、返回值:一个字符串列表,其中包含了由分隔符分隔的子字符串,即处理后的子字符串列表
- # 6、说明:
- # 6-1、如果sep不存在于字符串中,或者maxsplit设置为0或负数(且小于-1),则整个字符串将作为一个单独的子字符串返回
- # 7、示例:
- # 示例1:在空白处分割
- s = "Hello World"
- parts = s.split()
- print(parts) # 输出: ['Hello', 'World']
- # 示例2:指定分隔符
- s = "apple,banana,cherry"
- parts = s.split(",")
- print(parts) # 输出: ['apple', 'banana', 'cherry']
- # 示例3:指定分隔符和最大分割次数
- s = "apple,banana,cherry,date"
- parts = s.split(",", 2)
- print(parts) # 输出: ['apple', 'banana', 'cherry,date']
- # 示例4:如果分隔符不存在于字符串中
- s = "noseparatorhere"
- parts = s.split(",")
- print(parts) # 输出: ['noseparatorhere']
- # 示例5:指定空字符串作为分隔符
- s = "abc"
- parts = s.split("")
- # print(parts) # 报错:ValueError: empty separator
5-38、splitlines()方法
- # 1、方法:str.splitlines
- # 2、语法:str.splitlines([keepends])
- # 3、参数:
- # 3-1、keepends(可选):一个布尔值,指定是否在结果列表中保留行结束符(如'\n'或'\r\n');默认为False,表示不保留行结束符
- # 4、功能:用于将字符串按照行进行分割,返回一个包含各行作为元素的列表
- # 5、返回值:一个列表,其中包含了原始字符串中的各行,每行作为列表的一个元素
- # 6、说明:
- # 6-1、如果指定了keepends=True,则会在结果列表中保留行结束符
- # 6-2、默认情况下,不同类型的行结束符(如'\n'、'\r\n'和'\r')都会被识别并用于分割字符串,但在结果列表中不会保留这些行结束符
- # 7、示例:
- # 示例1:默认行为,不保留行结束符
- s = "Hello\nWorld\nHow are you?"
- lines = s.splitlines()
- print(lines) # 输出: ['Hello', 'World', 'How are you?']
- # 示例2:保留行结束符
- s = "Hello\nWorld\nHow are you?"
- lines = s.splitlines(keepends=True)
- print(lines) # 输出: ['Hello\n', 'World\n', 'How are you?']
- # 示例3:空字符串或只有空白字符的行也会被包含在内
- s = "\n\nHello\n\nWorld\n\n"
- lines = s.splitlines()
- print(lines) # 输出: ['', '', 'Hello', '', 'World', '']
- # 示例4:处理不同类型的行结束符
- s = "Hello\r\nWorld\nHow are you?\r"
- lines = s.splitlines()
- print(lines) # 输出: ['Hello', 'World', 'How are you?']
- # 注意:\r\n和\r都被视为行结束符,并且在结果中不保留
5-39、startswith()方法
- # 1、方法:str.startswith
- # 2、语法:str.startswith(prefix[, start[, end]])
- # 3、参数:
- # 3-1、prefix:要检查的前缀字符串
- # 3-2、start(可选):开始搜索的位置索引;默认为 0,表示从字符串的开始处进行搜索
- # 3-3、end(可选):停止搜索的位置索引(不包含该位置);默认为len(string),表示搜索到字符串的末尾
- # 4、功能:用于检查字符串是否以指定的前缀开始
- # 5、返回值:一个布尔值,表示字符串是否以指定的前缀开始
- # 6、说明:
- # 6-1、如果前缀为空字符串,则startswith()方法总是返回True,因为任何字符串都以空字符串开始
- # 7、示例:
- # 示例1:检查字符串是否以指定前缀开始
- s = "Hello, world!"
- print(s.startswith("Hello")) # 输出: True
- print(s.startswith("world")) # 输出: False
- # 示例2:指定开始搜索的位置索引
- s = "abcdefg"
- print(s.startswith("def", 3)) # 从索引3开始,因此"def"是从那里开始的,输出:True
- print(s.startswith("def", 4)) # 从索引4开始,因此"def"不是从那里开始的,输出:False
- # 示例3:指定开始和结束搜索的位置索引
- s = "abcdefg"
- print(s.startswith("cde", 2, 5)) # 从索引2开始,到索引5(不包含)结束,因此"cde"在这个范围内,输出:True
- print(s.startswith("cde", 2, 4)) # 从索引2开始,到索引4(不包含)结束,因此"cde"不在这个范围内,输出:False
- # 示例4:前缀为空字符串时总是返回True
- s = "Hello, world!"
- print(s.startswith("")) # 输出: True,因为任何字符串都以空字符串开始
5-40、strip()方法
- # 1、方法:str.strip
- # 2、语法:str.strip([chars])
- # 3、参数:
- # 3-1、chars(可选):一个字符串,指定要移除的字符集合;如果省略或为None,则移除字符串开头和结尾的所有空白字符
- # 4、功能:用于去除字符串开头和结尾的指定字符(默认为空白字符,包括空格、制表符、换行符等)
- # 5、返回值:一个新字符串,其中原始字符串开头和结尾的指定字符已被移除
- # 6、说明:
- # 7、示例:
- # 示例1:移除字符串开头和结尾的空白字符
- s = " Hello, world! "
- print(s.strip()) # 输出: "Hello, world!"
- # 示例2:移除字符串开头和结尾的指定字符
- s = "***Hello, world!***"
- print(s.strip("*")) # 输出: "Hello, world!"
- # 示例3:只移除字符串开头的字符
- s = "***Hello, world!"
- print(s.lstrip("*")) # 输出: "Hello, world!"
- # 示例4:只移除字符串结尾的字符
- s = "Hello, world!***"
- print(s.rstrip("*")) # 输出: "Hello, world!"
- # 示例5:移除字符串开头和结尾的多个指定字符
- s = "**Hello, world!!**"
- print(s.strip("!*")) # 输出: "Hello, world"
5-41、swapcase()方法
- # 1、方法:str.swapcase
- # 2、语法:str.swapcase()
- # 3、参数:无
- # 4、功能:用于将字符串中的所有小写字母转换为大写字母,同时将所有的大写字母转换为小写字母
- # 5、返回值:一个新字符串,只是原字符串中的大写字母转小写,小写字母转大写
- # 6、说明:
- # 7、示例:
- # 示例1:将字符串中的大小写字母互换
- s = "Hello, World!"
- swapped = s.swapcase()
- print(swapped) # 输出: "hELLO, wORLD!"
- # 示例2:包含数字和非字母字符的字符串
- s = "Hello123World"
- swapped = s.swapcase()
- print(swapped) # 输出: "hELLO123wORLD",数字和非字母字符保持不变
- # 示例3:空字符串或只包含小写字母的字符串
- s = ""
- swapped = s.swapcase()
- print(swapped) # 输出: "",空字符串保持不变
- s = "hello"
- swapped = s.swapcase()
- print(swapped) # 输出: "HELLO",所有小写字母被转换为大写字母
- # 示例4:只包含大写字母的字符串
- s = "HELLO"
- swapped = s.swapcase()
- print(swapped) # 输出: "hello",所有大写字母被转换为小写字母
5-42、title()方法
- # 1、方法:str.title
- # 2、语法:str.title()
- # 3、参数:无
- # 4、功能:用于将字符串中的每个单词的首字母转换为大写,而其余字母转换为小写
- # 5、返回值:一个新的字符串
- # 6、说明:
- # 7、示例:
- # 示例1:将字符串中的每个单词首字母转换为大写
- s = "hello, world!"
- titled = s.title()
- print(titled) # 输出: "Hello, World!"
- # 示例2:包含标点符号的字符串
- s = "hello-world, this is a test"
- titled = s.title()
- print(titled) # 输出: "Hello-World, This Is A Test"
- # 注意,标点符号后的单词也被视为独立的单词,并且其首字母也被转换为大写
- # 示例3:只包含小写字母的字符串
- s = "hello"
- titled = s.title()
- print(titled) # 输出: "Hello"
- # 示例4:只包含大写字母的字符串
- s = "HELLO"
- titled = s.title()
- print(titled) # 输出: "Hello"
- # 注意,尽管原始字符串全部为大写,但title()方法仍然将其视为单个单词,
- # 并将其转换为首字母大写,其余字母小写的形式
- # 示例5:包含非字母字符的字符串
- s = "123hello456world"
- titled = s.title()
- print(titled) # 输出: "123Hello456World"
- # 非字母字符前后的字母都被视为独立单词的首字母,并被转换为大写
5-43、translate()方法
- # 1、方法:str.translate
- # 2、语法:str.translate(table)
- # 3、参数:table是一个字典或str.maketrans()函数创建的转换表
- # 4、功能:用于根据一个转换表(translation table)来替换字符串中的字符
- # 5、返回值:一个新的字符串
- # 6、说明:
- # 6-1、translate()方法是高度优化的,通常比使用循环和条件语句来替换或删除字符要快得多
- # 6-2、在处理大型字符串或需要频繁进行字符替换时,使用translate()方法是一个很好的选择
- # 7、示例:
- # 示例1:使用maketrans和translate替换字符
- intab = "aeiou"
- outtab = "12345"
- trantab = str.maketrans(intab, outtab)
- str = "this is an example for translate"
- new_str = str.translate(trantab)
- print(new_str) # 输出: 'th3s 3s 1n 2x1mpl2 f2r tr1nsl173'
- # 示例2:删除字符串中的特定字符
- # 使用字典创建转换表,将需要删除的字符映射到None
- table = {ord(' '): None, ord(','): None, ord('.'): None}
- str = "hello, world. this is a test."
- new_str = str.translate(table)
- print(new_str) # 输出: 'helloworldthisisatest'
- # 注意:ord()函数用于获取字符的Unicode字符点(即整数值)
5-44、upper()方法
- # 1、方法:str.upper
- # 2、语法:str.upper()
- # 3、参数:无
- # 4、功能:用于将字符串中的所有小写字母转换为大写字母
- # 5、返回值:一个新的字符串,其中原始字符串中的小写字母已经被转换为大写,而原始字符串本身不会被修改
- # 6、说明:
- # 7、示例:
- # 示例1:将字符串中的小写字母转换为大写
- s = "hello, world!"
- upper_s = s.upper()
- print(upper_s) # 输出: "HELLO, WORLD!"
- # 示例2:包含数字和标点符号的字符串
- s = "Hello123World!"
- upper_s = s.upper()
- print(upper_s) # 输出: "HELLO123WORLD!"
- # 注意,数字和标点符号保持不变
- # 示例3:只包含大写字母的字符串
- s = "HELLO"
- upper_s = s.upper()
- print(upper_s) # 输出: "HELLO"
- # 如果字符串已经是大写,则upper()不会改变它
- # 示例4:空字符串
- s = ""
- upper_s = s.upper()
- print(upper_s) # 输出: ""
- # 空字符串保持不变
- # 示例5:包含非字母字符的字符串
- s = "h1e2l3l4o"
- upper_s = s.upper()
- print(upper_s) # 输出: "H1E2L3L4O"
- # 非字母字符保持不变
5-45、zfill()方法
- # 1、方法:str.zfill
- # 2、语法:str.zfill(width)
- # 3、参数:width,表示期望的字符串总长度
- # 4、功能:用于在字符串的左边填充零('0'),直到达到指定的总长度
- # 5、返回值:一个新的字符串
- # 6、说明:如果字符串已经足够长或超过了指定的长度,则不会进行任何更改
- # 7、示例:
- # 示例1:填充零以达到指定长度
- s = "42"
- filled_s = s.zfill(5)
- print(filled_s) # 输出: "00042"
- # 示例2:如果字符串已经足够长,则不做任何更改
- s = "12345"
- filled_s = s.zfill(4)
- print(filled_s) # 输出: "12345"
- # 示例3:填充零以用于数字字符串,如月份或日期
- month = "7"
- filled_month = month.zfill(2)
- print(filled_month) # 输出: "07"
- # 示例4:如果字符串包含非数字字符,则在左边填充零
- s = "abc"
- filled_s = s.zfill(6)
- print(filled_s) # 输出: "000abc"
二、推荐阅读
1、Python-VBA函数之旅-str()函数
2、Python算法之旅
3、Python函数之旅
4、个人主页-神奇夜光杯-CSDN

遨游码海,我心飞扬
微信名片


注:本文转载自blog.csdn.net的神奇夜光杯的文章"https://myelsa1024.blog.csdn.net/article/details/139043773"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
评论记录:
回复评论: