栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python中字符串的方法详解

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python中字符串的方法详解

Python中字符串的方法详解 | 1,capitalize(self, /) 返回一个 首字母大写,其余所有字母小写的新字符串

| Return a capitalized version of the string.
|
| More specifically, make the first character have upper case and the rest lower
| case.

| 2,casefold(self, /) 返回一个将所有字母转换为小写的字符串

| Return a version of the string suitable for caseless comparisons.

| 3,center(self, width, fillchar=’ ', /) 返回一个 居中的新字符串,可以自行设置宽度和填充字符

| Return a centered string of length width.
|
| Padding is done using the specified fill character (default is a space).

| 4,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.

| 5,encode(self, /, encoding=‘utf-8’, errors=‘strict’) 以指定的编码格式编码字符串,默认编码为 ‘utf-8’

| 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.

| 6,endswith(…) 判断字符串是否以指定字符作为结尾,返回值为bool类型

| 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.
| [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QWYJLuYv-1655865307372)(C:UserschendafaAppDataRoamingTyporatypora-user-imagesimage-20220620182758965.png)]

| 7,expandtabs(self, /, tabsize=8) 将字符串S中的 t 替换为一定数量的空格。默认N=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.
| [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-F89t31F1-1655865307374)(C:/Users/chendafa/AppData/Roaming/Typora/typora-user-images/image-20220622094853290.png)

| 8, find(…) 查找字符串中指定的子字符串sub第一次出现的位置,可以规定字符串的索引查找范围。若无则返回 -1。

| 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.
|

| 9,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 ‘}’).
|

| 10,index(…) 查找字符串中第一次出现的子字符串的位置,可以规定字符串的索引查找范围[star,end)。若无则会报错。

| 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.

| 11,isalnum(self, /) 判断字符串是否由字符和数字组成,str中至少有一个字符且所有字符都是字母或数字则返回 True,否则返回 False

| 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.

| 12, isalpha(self, /) 检测字符串是否只由字母组成。字符串中至少有一个字符且所有字符都是字母则返回 True,否则返回 False。

| 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.

| 13,isascii(self, /) 如果字符串为空或字符串中的所有字符都是 ASCII,则返回 True,否则返回 False

| 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.

| 14, isdecimal(self, /) 检查字符串是否只包含十进制字符。字符串中若只包含十进制字符返回True,否则返回False。该方法只存在于unicode对象中。注意:定义一个十进制字符串,只需要在字符串前添加前缀 ‘u’ 即可。

| 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.

| 15,isdigit(self, /) 检测字符串是否只由数字组成.字符串中至少有一个字符且所有字符都是数字则返回 True,否则返回 False。

| 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.

| 16,isidentifier(self, /) 判断str是否是有效的标识符。str为符合命名规则的变量,保留标识符则返回True,否者返回False

| 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”.

| 17,islower(self, /) 检测字符串中的字母是否全由小写字母组成。(字符串中可包含非字母字符)字符串中包含至少一个区分大小写的字符,且所有这些区分大小写的字符都是小写,则返回 True,否则返回 False。

| 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.
|

| 18,isnumeric(self, /) 检测字符串是否只由数字组成。这种方法是只适用于unicode对象。字符串中只包含数字字符,则返回 True,否则返回 False。

| 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.

| 19,isprintable(self, /) 判断字符串中是否有打印后不可见的内容。如:n t 等字符。若字符串中不存在n t 等不可见的内容,则返回True,否者返回False。

| 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.

| 20,isspace(self, /) 检测字符串是否只由空格组成。若字符串中只包含空格,则返回 True,否则返回 False。

| 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.

| 21,istitle(self, /) 检测判断字符串中所有单词的首字母是否为大写,且其它字母是否为小写,字符串中可以存在其它非字母的字符。若字符串中所有单词的首字母为大写,且其它字母为小写,则返回 True,否则返回 False.

| 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.

| 22,isupper(self, /) 检测字符串中的字母是否全由大写字母组成。(字符串中可包含非字母字符)。字符串中包含至少一个区分大小写的字符,且所有这些区分大小写的字符都是大写,则返回 True,否则返回 False。

| 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.
|

| 23, join(self, iterable, /) 将iterable变量的每一个元素后增加一个str字符串。

| 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’

| 24, ljust(self, width, fillchar=’ ', /) 返回一个原字符串左对齐,并使用fillchar填充(默认为空格)至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

| Return a left-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).

| 25, lower(self, /) 返回一个所有字母小写的新字符串

| Return a copy of the string converted to lowercase.

| 26, lstrip(self, chars=None, /) 返回一个原字符串左对齐,并使用fillchar填充(默认为空格)至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

| Return a copy of the string with leading whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|

| 27,partition(self, sep, /) 根据指定的分隔符(sep)将字符串进行分割。从字符串左边开始索引分隔符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.
|

|28, 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.

| 29, 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.

|30, replace(self, old, new, count=-1, /) 把str.中的 old 替换成 new,如果 count 指定,则替换不超过 count次.。

| 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.

| 31, rfind(…) 查找字符串中指定的子字符串sub最后一次出现的位置,可以规定字符串的索引查找范围。若无则返回 -1。

| 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.

| 32, rindex(…) rindex() 方法返回子字符串最后一次出现在字符串中的索引位置,该方法与 rfind() 方法一样,可以规定字符串的索引查找范围[star,end),只不过如果子字符串不在字符串中会报一个异常。

| 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.

| 33, rjust(self, width, fillchar=’ ', /) 返回一个原字符串右对齐,并使用fillchar填充(默认为空格)至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

| Return a right-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).

|34, rpartition(self, sep, /) 根据指定的分隔符(sep)将字符串进行分割。从字符串右边(末尾)开始索引分隔符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.

| 35, rsplit(self, /, sep=None, maxsplit=-1) 拆分字符串。通过指定分隔符sep对字符串进行分割,并返回分割后的字符串列表,类似于split()函数,只不过 rsplit()函数是从字符串右边(末尾)开始分割。

| 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.
|
| Splits are done starting at the end of the string and working to the front.

|36, rstrip(self, chars=None, /) 删除 str 字符串末尾的指定字符(默认为空格)

| Return a copy of the string with trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.

|37, split(self, /, sep=None, maxsplit=-1) 拆分字符串。通过指定分隔符sep对字符串进行分割,并返回分割后的字符串列表。

| 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.

| 38, splitlines(self, /, keepends=False) 按照(‘n’, ‘r’, rn’等)分隔,返回一个包含各行作为元素的列表,默认不包含换行符。n 换行符 r 回车符 rn 回车+换行

| 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.
|

| 39, 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.
|

|40, 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.
|

| 41, swapcase(self, /) 将字符串str中的大小写字母同时进行互换。即将字符串str中的大写字母转换为小写字母,将小写字母转换为大写字母。

| Convert uppercase characters to lowercase and lowercase characters to uppercase.

| 42, 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.
|

| 43, translate(self, table, /) 过滤(删除),翻译字符串。即根据maketrans()函数给出的字符映射转换表来转换字符串中的字符。

注:translate()函数是先过滤(删除),再根据maketrans()函数返回的转换表来翻译。

| 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.
|

| 44, upper(self, /) 将字符串中的所有小写字母转换为大写字母

| Return a copy of the string converted to uppercase.

| 45, zfill(self, width, /) 返回指定长度的字符串,使原字符串右对齐,前面用0填充到指定字符串长度。

| Pad a numeric string with zeros on the left, to fill a field of the given width.
|
| The string is never truncated.

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/982421.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号