目录
一、字符串
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-16、isidentifier()函数
- # Python的keyword模块和str类型的一些特性可以用于判断一个字符串是否可能是一个有效的标识符(identifier,例如变量名、函数名等)
- # 一个有效的Python标识符需要满足以下条件:
- # 1、它必须以字母(包括大小写)或下划线_开始
- # 2、它后面可以跟任意数量的字母、数字或下划线
- # 3、它不能是Python的关键字
- # 为了检查一个字符串是否可能是有效的标识符(不考虑关键字),你可以使用正则表达式
- # 如果你还希望排除Python的关键字,那么你需要使用keyword模块来检查字符串是否是关键字
- import re
- import keyword
- def isidentifier(s):
- # 使用正则表达式检查字符串是否符合标识符的基本格式
- if not re.match(r'^[a-zA-Z_]\w*$', s):
- return False
- # 使用keyword模块检查字符串是否是Python的关键字
- if keyword.iskeyword(s):
- return False
- return True
- # 示例
- print(isidentifier('my_variable')) # 输出: True
- print(isidentifier('123abc')) # 输出: False(以数字开头)
- print(isidentifier('class')) # 输出: False(是关键字)
5-17、islower()方法
- # 1、方法:str.islower
- # 2、语法:str.islower()
- # 3、参数:无
- # 4、功能:用于检查字符串中的所有字符是否都是小写
- # 5、返回值:一个布尔值
- # 6、说明:
- # 6-1、如果字符串中的所有字符都是小写,则返回True,否则返回False
- # 7、示例:
- # 示例
- s1 = "hello"
- print(s1.islower()) # 输出: True
- s2 = "Hello"
- print(s2.islower()) # 输出: False
- s3 = "hello123"
- print(s3.islower()) # 输出: True,因为数字不是字母,不影响判断
- s4 = "hello World"
- print(s4.islower()) # 输出: False,因为包含大写字母W
- s5 = ""
- print(s5.islower()) # 输出: False,因为包含空字符串
- s6 = "hello\nworld"
- print(s6.islower()) # 输出: True,因为换行符等非字母字符,不影响判断
- s7 = "⅛" #(这里使用的是分数形式的数字)
- print(s7.isdigit()) # 输出: False,因为包含非数字字符
5-18、isnumeric()方法
- # 1、方法:str.isnumeric
- # 2、语法:str.isnumeric()
- # 3、参数:无
- # 4、功能:用来检查字符串是否只包含数字字符
- # 5、返回值:一个布尔值
- # 6、说明:
- # 6-1、如果字符串中的所有字符都是数字并且字符串至少包含一个字符,则返回True,否则返回False
- # 6-2、isnumeric()方法仅适用于Unicode数字字符,如阿拉伯数字(0-9)和一些其他Unicode数字字符,但不适用于罗马数字、百分号、千位分隔符等
- # 6-3、如果你需要更广泛的数字检查(包括浮点数、指数形式等),你可能需要使用正则表达式或其他方法
- # 7、示例:
- # 示例
- s1 = "12345"
- print(s1.isnumeric()) # 输出: True
- s2 = "123abc"
- print(s2.isnumeric()) # 输出: False,因为包含非数字字符
- s3 = "0x123"
- print(s3.isnumeric()) # 输出: False,因为包含非数字字符
- s4 = ""
- print(s4.isnumeric()) # 输出: False,空字符串不包含任何数字字符
- s5 = "123.456"
- print(s5.isnumeric()) # 输出: False,因为包含小数点
- s6 = "123 "
- print(s6.isnumeric()) # 输出: False,因为包含空格
5-19、isprintable()函数
- # 以下是一个示例函数,它检查一个字符串是否仅包含可打印的字符
- import unicodedata
- def isprintable(s):
- for char in s:
- # 获取字符的Unicode类别
- category = unicodedata.category(char)
- # 控制字符通常以'C'开头
- if category.startswith('C'):
- return False
- return True
- # 测试
- print(isprintable("Hello, World!")) # 输出: True
- print(isprintable("\nThis string contains a newline character\n")) # 输出: False
5-20、isspace()方法
- # 1、方法:str.isspace
- # 2、语法:str.isspace()
- # 3、参数:无
- # 4、功能:用于检查字符串是否只包含空白字符
- # 5、返回值:一个布尔值
- # 6、说明:
- # 6-1、空白字符包括空格、制表符(\t)、换行符(\n)、回车符(\r)、换页符(\f)和垂直制表符(\v)
- # 6-2、如果字符串中只包含空白字符,则该方法返回 True;否则返回 False
- # 6-3、空字符串(即没有字符的字符串)""不会返回True,因为它不含任何字符(包括空白字符),只有包含至少一个空白字符且只包含空白字符的字符串才会返回True
- # 7、示例:
- # 示例 1:只包含空格的字符串
- s1 = " "
- print(s1.isspace()) # 输出: True
- # 示例 2:包含非空白字符的字符串
- s2 = "Hello, World!"
- print(s2.isspace()) # 输出: False
- # 示例 3:包含空格和其他字符的字符串
- s3 = "Hello World "
- print(s3.isspace()) # 输出: False
- # 示例 4:只包含制表符的字符串
- s4 = "\t\t\t"
- print(s4.isspace()) # 输出: True
- # 示例 5:包含换行符的字符串
- s5 = "\n\n"
- print(s5.isspace()) # 输出: True
- # 示例 6:空字符串
- s6 = ""
- print(s6.isspace()) # 输出: False(空字符串不包含任何字符,因此不被认为是只包含空白字符)
5-21、istitle()方法
- # 1、方法:str.istitle
- # 2、语法:str.istitle()
- # 3、参数:无
- # 4、功能:用于检查字符串是否是一个标题化的字符串
- # 5、返回值:一个布尔值
- # 6、说明:
- # 6-1、一个标题化的字符串意味着字符串中的每个单词的首字母都是大写,其余字母都是小写,并且单词之间由空白字符分隔
- # 6-2、如果字符串是标题化的,则该方法返回True;否则返回False
- # 7、示例:
- # 示例 1:标题化的字符串
- s1 = "Hello World"
- print(s1.istitle()) # 输出: True
- # 示例 2:非标题化的字符串(包含大写字母但不是每个单词的首字母)
- s2 = "Hello world"
- print(s2.istitle()) # 输出: False
- # 示例 3:非标题化的字符串(包含小写字母开头的单词)
- s3 = "hello World"
- print(s3.istitle()) # 输出: False
- # 示例 4:包含非字母字符的标题化字符串
- s4 = "Hello-World"
- print(s4.istitle()) # 输出: True
- # 示例 5:空字符串
- s5 = ""
- print(s5.istitle()) # 输出: False,因为空字符串不包含任何字母字符
- # 示例 6:只包含大写字母的字符串(不是标题化,因为没有小写字母)
- s6 = "HELLO WORLD"
- print(s6.istitle()) # 输出: False
- # 示例 7:包含数字和其他字符的标题化字符串
- s7 = "The 1st Example"
- print(s7.istitle()) # 输出: False,因为1st以数字开头
5-22、isupper()方法
- # 1、方法:str.isupper
- # 2、语法:str.isupper()
- # 3、参数:无
- # 4、功能:用于检查字符串中的所有字母字符是否都是大写
- # 5、返回值:一个布尔值
- # 6、说明:
- # 6-1、如果字符串中的所有字母字符都是大写,则该方法返回True;否则返回False
- # 6-2、isupper()方法只关注字母字符,并忽略非字母字符(如数字、标点符号和空格),只要字符串中的所有字母字符都是大写,那么该字符串就被认为是全大写的
- # 7、示例:
- # 示例 1:全大写的字符串
- s1 = "HELLO WORLD"
- print(s1.isupper()) # 输出: True
- # 示例 2:包含小写字母的字符串
- s2 = "Hello World"
- print(s2.isupper()) # 输出: False
- # 示例 3:只包含大写字母和数字的字符串
- s3 = "HELLO123"
- print(s3.isupper()) # 输出: True,因为只检查字母字符,数字不影响结果
- # 示例 4:空字符串
- s4 = ""
- print(s4.isupper()) # 输出: False,因为空字符串不包含任何字母字符
- # 示例 5:包含非字母字符的字符串
- s5 = "HELLO-WORLD"
- print(s5.isupper()) # 输出: True,因为'-'不是字母字符,不影响结果
- # 示例 6:只包含小写字母的字符串
- s6 = "hello world"
- print(s6.isupper()) # 输出: False
- # 示例 7:包含非ASCII字符的字符串(如果它们是大写的话)
- s7 = "ЗДРАВСТВУЙТЕ" # 俄语中的“你好”
- print(s7.isupper()) # 输出: True(取决于你的Python版本和环境对Unicode的支持)
5-23、join()方法
- # 1、方法:str.join
- # 2、语法:str.join(iterable)
- # 3、参数:
- # 3-1、iterable,表示一个可迭代对象,如列表、元组或字符串迭代器,其中的元素都是字符串
- # 4、功能:用于将序列(如列表、元组或字符串迭代器)中的元素以指定的字符或字符串作为分隔符连接生成一个新的字符串
- # 5、返回值:一个新的字符串
- # 6、说明:
- # 6-1、join()方法是在作为分隔符的字符串上调用的,而不是在要连接的元素上
- # 7、示例:
- # 示例 1:使用空格作为分隔符连接字符串列表
- words = ["Hello", "World"]
- result = " ".join(words)
- print(result) # 输出: Hello World
- # 示例 2:使用逗号作为分隔符连接字符串列表
- items = ["apple", "banana", "cherry"]
- result = ", ".join(items)
- print(result) # 输出: apple, banana, cherry
- # 示例 3:使用空字符串连接列表中的字符串,相当于拼接字符串
- chars = ["H", "e", "l", "l", "o"]
- result = "".join(chars)
- print(result) # 输出: Hello
- # 示例 4:尝试使用非字符串元素进行连接会抛出TypeError
- numbers = [1, 2, 3]
- # result = " ".join(numbers) # 这行会抛出TypeError,因为numbers中的元素不是字符串
- # 为了避免这个错误,可以先将列表中的元素转换为字符串
- numbers_str = [str(num) for num in numbers]
- result = " ".join(numbers_str)
- print(result) # 输出: 1 2 3
5-24、ljust()方法
- # 1、方法:str.ljust
- # 2、语法:str.ljust(width[, fillchar])
- # 3、参数:
- # 3-1、width(必须):新字符串的长度;如果指定长度小于原始字符串的长度,则返回原始字符串
- # 3-2、fillchar(可选):用于填充的字符,默认为空格
- # 4、功能:用于返回一个原字符串左对齐,并使用指定的填充字符(默认为空格)填充至指定长度的新字符串
- # 5、返回值:一个指定长度的新字符串
- # 6、说明:
- # 7、示例:
- # 示例 1:左对齐,使用空格填充至长度为10的新字符串
- s = "Hello"
- result = s.ljust(10)
- print(result) # 输出: "Hello "
- # 示例 2:左对齐,指定填充字符为'*',填充至长度为10的新字符串
- s = "Hello"
- result = s.ljust(10, '*')
- print(result) # 输出: "Hello*****"
- # 示例 3:原字符串长度超过指定长度,直接返回原字符串
- s = "Hello World"
- result = s.ljust(10)
- print(result) # 输出: "Hello World",因为长度已经超过10,所以直接返回原字符串
5-25、lower()方法
- # 1、方法:str.lower
- # 2、语法:str.lower()
- # 3、参数:无
- # 4、功能:用于将字符串中的所有大写字母转换为小写字母
- # 5、返回值:返回一个新的字符串,其中包含原始字符串的小写版本
- # 6、说明:该方法不会修改原始的字符串,而是返回一个新的字符串,其中包含原始字符串的小写版本
- # 7、示例:
- # 示例 1:将字符串转换为小写
- s = "Hello World"
- lowercase_s = s.lower()
- print(lowercase_s) # 输出: hello world
- # 示例 2:字符串中已经全部是小写,不会改变结果
- s = "hello world"
- lowercase_s = s.lower()
- print(lowercase_s) # 输出: hello world
- # 示例 3:包含非字母字符的字符串,只会转换字母部分
- s = "Hello123World"
- lowercase_s = s.lower()
- print(lowercase_s) # 输出: hello123world
- # 示例 4:空字符串或只包含非字母字符的字符串,返回相同的字符串
- s = ""
- lowercase_s = s.lower()
- print(lowercase_s) # 输出: ""
- s = "!@#"
- lowercase_s = s.lower()
- print(lowercase_s) # 输出: "!@#"
5-26、lstrip()方法
- # 1、方法:str.lstrip
- # 2、语法:str.lstrip([chars])
- # 3、参数:
- # 3-1、chars(可选):指定需要去除的字符集合;如果未指定或为空,则默认去除空白字符,字符集合可以是字符串,表示要去除的字符序列
- # 4、功能:用于去除字符串左侧的空白字符(包括空格、换行符、制表符等)或指定的字符
- # 5、返回值:返回一个新的字符串,不影响原始字符串
- # 6、说明:如果字符串左侧没有需要去除的字符,则返回原始字符串
- # 7、示例:
- # 示例 1:去除字符串左侧的空白字符
- s = " Hello World "
- left_stripped = s.lstrip()
- print(left_stripped) # 输出: "Hello World "
- # 示例 2:指定要去除的字符集合
- s = "***Hello World***"
- left_stripped = s.lstrip("*")
- print(left_stripped) # 输出: "Hello World***"
- # 示例 3:如果字符串左侧没有要去除的字符,则返回原始字符串
- s = "Hello World"
- left_stripped = s.lstrip()
- print(left_stripped) # 输出: "Hello World"
- # 示例 4:指定要去除的字符集合中包含多个字符
- s = "abcHello Worldabc"
- left_stripped = s.lstrip("abc")
- print(left_stripped) # 输出: "Hello Worldabc"
5-27、partition()方法
- # 1、方法:str.partition
- # 2、语法:str.partition(sep)
- # 3、参数:
- # 3-1、sep:用于分割字符串的分隔符
- # 4、功能:用于将字符串分割为三部分,返回一个包含三个元素的元组,这三个元素分别是:分隔符之前的子串、分隔符本身以及分隔符之后的子串
- # 5、返回值:返回包含三部分(分隔符之前的部分、分隔符本身和分隔符之后的部分)的元组
- # 6、说明:如果字符串中不包含指定的分隔符,则返回包含原始字符串和两个空字符串的元组
- # 7、示例:
- # 示例 1:分割包含分隔符的字符串
- s = "Hello-World"
- parts = s.partition("-")
- print(parts) # 输出: ('Hello', '-', 'World')
- # 示例 2:分隔符在字符串开头
- s = "-Hello-World"
- parts = s.partition("-")
- print(parts) # 输出: ('', '-', 'Hello-World')
- # 示例 3:分隔符在字符串结尾
- s = "Hello-World-"
- parts = s.partition("-")
- print(parts) # 输出: ('Hello', '-', 'World-')
- # 示例 4:字符串中不包含分隔符
- s = "HelloWorld"
- parts = s.partition("-")
- print(parts) # 输出: ('HelloWorld', '', '')
- # 示例 5:分隔符多次出现,但只分割第一次出现的位置
- s = "Hello-World-Example"
- parts = s.partition("-")
- print(parts) # 输出: ('Hello', '-', 'World-Example')
5-28、removeprefix()方法
- # 1、方法:str.removeprefix
- # 2、语法:str.removeprefix(prefix)
- # 3、参数:
- # 3-1、prefix:要删除的前缀字符串
- # 4、功能:用于从字符串的开头删除指定的前缀(仅适用于Python 3.9及以上版本)
- # 5、返回值:一个新的字符串
- # 6、说明:如果字符串以指定的前缀开头,则返回删除前缀后的字符串;否则,返回原始字符串
- # 7、示例:
- # 示例 1:从字符串开头删除前缀
- s = "prefix_Hello_World"
- s_without_prefix = s.removeprefix("prefix_")
- print(s_without_prefix) # 输出: "Hello_World"
- # 示例 2:字符串不以指定前缀开头,返回原始字符串
- s = "Hello_World"
- s_without_prefix = s.removeprefix("prefix_")
- print(s_without_prefix) # 输出: "Hello_World"
- # 示例 3:前缀为空字符串,返回原始字符串
- s = "Hello_World"
- s_without_prefix = s.removeprefix("")
- print(s_without_prefix) # 输出: "Hello_World"
- # 示例 4:前缀与字符串相等,返回空字符串
- s = "prefix_"
- s_without_prefix = s.removeprefix("prefix_")
- print(s_without_prefix) # 输出: ""
5-29、removesuffix()方法
- # 1、方法:str.removesuffix
- # 2、语法:str.removesuffix(suffix)
- # 3、参数:
- # 3-1、suffix:要删除的后缀字符串
- # 4、功能:用于从字符串的末尾删除指定的后缀(仅适用于Python 3.9及以上版本)
- # 5、返回值:一个新的字符串
- # 6、说明:如果字符串以指定的后缀结尾,则返回删除后缀后的字符串;否则,返回原始字符串
- # 7、示例:
- # 示例 1:从字符串末尾删除后缀
- s = "Hello_World_suffix"
- s_without_suffix = s.removesuffix("_suffix")
- print(s_without_suffix) # 输出: "Hello_World"
- # 示例 2:字符串不以指定后缀结尾,返回原始字符串
- s = "Hello_World"
- s_without_suffix = s.removesuffix("_suffix")
- print(s_without_suffix) # 输出: "Hello_World"
- # 示例 3:后缀为空字符串,返回原始字符串
- s = "Hello_World"
- s_without_suffix = s.removesuffix("")
- print(s_without_suffix) # 输出: "Hello_World"
- # 示例 4:后缀与字符串相等,返回空字符串
- s = "_suffix"
- s_without_suffix = s.removesuffix("_suffix")
- print(s_without_suffix) # 输出: ""
5-30、replace()方法
- # 1、方法:str.replace
- # 2、语法:str.replace(old, new[, count])
- # 3、参数:
- # 3-1、old(必须):需要被替换的子串
- # 3-2、new(必须):用于替换的子串
- # 3-3、count(可选):替换的最大次数;如果省略或为-1,则替换所有出现的子串
- # 4、功能:用于在字符串中查找并替换指定的子串,该方法会返回一个新的字符串,其中指定的子串(或所有出现的子串)已被新的子串替换
- # 5、返回值:一个新的字符串
- # 6、说明:如果old参数指定的子串在原始字符串中不存在,则replace()方法会返回原始字符串
- # 7、示例:
- # 示例 1:替换所有出现的子串
- s = "Hello, world! world is beautiful."
- s_replaced = s.replace("world", "Python")
- print(s_replaced) # 输出: "Hello, Python! Python is beautiful."
- # 示例 2:替换指定次数的子串
- s = "apple, apple, apple pie"
- s_replaced = s.replace("apple", "orange", 2)
- print(s_replaced) # 输出: "orange, orange, apple pie"
- # 示例 3:如果子串不存在于原始字符串中,则不执行替换
- s = "banana, banana split"
- s_replaced = s.replace("apple", "orange")
- print(s_replaced) # 输出: "banana, banana split"(没有变化)
- # 示例 4:使用空字符串作为替换字符串,可以删除指定子串
- s = "aaa123bbb456ccc"
- s_replaced = s.replace("bbb", "")
- print(s_replaced) # 输出: "aaa123456ccc"
二、推荐阅读
1、Python-VBA函数之旅-str()函数
2、Python算法之旅
3、Python函数之旅
4、个人主页-神奇夜光杯-CSDN

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


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