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

Python-所有字符串函数总结

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

Python-所有字符串函数总结

直接看文档是按顺序排列的有点乱,总结分类下,同时写一些备注,方便以后理解查阅

分类函数解释例子
查询S.find(sub[, start[, end]]) -> intReturn 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
S.rfind(sub[, start[, end]]) -> intReturn 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.
s = "abab"
s.rfind("ab")
return 2
S.index(sub[, start[, end]]) -> intReturn 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.
S.rindex(sub[, start[, end]]) -> intReturn 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.
大小写S.upper() -> strReturn a copy of S converted to uppercase.
S.lower() -> strReturn a copy of the string S converted to lowercase.
S.casefold() -> strReturn a version of S suitable for caseless comparisons.
casefold()对于非英文的其他语言小写也有效
S.swapcase() -> strReturn a copy of S with uppercase characters converted to lowercase and vice versahellO World
⬇
HELLo wORLD
S.capitalize() -> strReturn a capitalized version of S, i.e. make the first character have upper case and the rest lower case.hellO World
⬇
Hello world
S.title() -> strReturn a titlecased version of S, i.e. words start with title case characters, all remaining cased characters have lower case.hellO World
⬇
Hello World
对齐S.center(width[, fillchar]) -> strReturn S centered in a string of length width.

Padding is done using the specified fill character (default is a space)
S.ljust(width[, fillchar]) -> strReturn S left-justified in a Unicode string of length width.

Padding is done using the specified fill character (default is a space).
S.rjust(width[, fillchar]) -> strReturn S right-justified in a string of length width.

Padding is done using the specified fill character (default is a space).
S.zfill(width) -> strPad a numeric string S with zeros on the left, to fill a field of the specified width.

The string S is never truncated
(对字符串做改变的都不会改变原字符串).
分割S.split(sep=None, maxsplit=-1)
-> list of strings
Return a list of the words in S, using sep as the delimiter string.

If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.

If maxsplit is given, at most maxsplit splits are done.
例1
‘a b c’.split()
⬇
[‘a’, ‘b’, ‘c’]

例2
‘a b c’.split(’ ', 1)
⬇
[‘a’, ‘b c’]
S.rsplit(sep=None, maxsplit=-1)
-> list of strings
Return a list of the words in S, using sep as the delimiter string, starting at the end of the string and working to the front.

If maxsplit is given, at most maxsplit splits are done.

If sep is not specified, any whitespace string
is a separator.
例1
‘a b c’.split()
⬇
[‘a’, ‘b’, ‘c’]

例2
体现split和rsplit区别
‘a b c’.split(’ ', 1)
⬇
[‘a b’, ’ c’]
S.splitlines([keepends])
-> list of strings
Return a list of the lines in S, breaking at line boundaries Line breaks are not included in the resulting list unless keepends is given and true.
S.partition(sep)
-> (head, sep, tail)
Search for the separator sep in S, and return the part before it, the separator itself, and the part after it.

If the separator is not found, return S and two empty strings.

(从头开始找,返回一个tuple)
S.rpartition(sep) -> (head, sep, tail)Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it.

If the separator is not found, return two empty strings and S.

(从后往前找)
合并S.join(iterable) -> strReturn a string which is the concatenation of the strings in the iterable.

The separator between elements is S
d = 'abc'
", ".join(d)
⬇
'a, b, c'
d只要iterable
不一定是字符串
替换S.replace(old, new[, count]) -> strReturn a copy of S with all occurrences of substring old replaced by new.

If the optional argument count is given, only the first count occurrences are replaced
判断S.isidentifier() -> boolReturn True if S is a valid identifier according to the language definition.

Use keyword.iskeyword() to test for reserved identifiers such as “def” and “class”.

可用来判断变量名是否合法
S.isspace() -> boolReturn True if all characters in S are whitespace and there is at least one character in S, False otherwise.

(whitespace: 空白、回车、换行和水平制表符)
S.isalpha() -> boolReturn True if all characters in S are alphabetic
and there is at least one character in S, False otherwise
S.isdecimal() -> boolReturn True if there are only decimal characters in S, False otherwise.

判断是不是十进制数

True: 阿拉伯数字
False: 罗马数字,汉字数字
Error: byte数字(单字节)b'1'
S.isdigit() -> boolReturn True if all characters in S are digits and there is at least one character in S, False otherwise.

True:阿拉伯数字,byte数字,罗马数字
False: 汉字数字
Error: 无
S.isnumeric() -> boolReturn True if there are only numeric characters in S, False otherwise.

True: 阿拉伯数字,罗马数字,汉字数字
False: 无
Error: byte数字(单字节)
S.isalnum() -> boolReturn True if all characters in S are alphanumeric and there is at least one character in S,
False otherwise.
S.islower() -> boolReturn True if all cased characters in S are lowercase and there is at least one cased character in S, False otherwise.
S.isupper() -> boolReturn True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise.
S.istitle() -> boolReturn True if S is a titlecased string and there is at least one character in S, i.e. upper- and titlecase characters may only follow uncased characters and lowercase characters only cased ones.
Return False otherwise.
‘This Is A Title’
S.isprintable() -> boolReturn True if all characters in S are considered
printable in repr() or S is empty,
False otherwise.

n就是不可打印
比较>, >=, <, <=, ==, !=从第一个依次往下比较,比较oridinal value(原始值)
ord(ch)将指定字符转为原始值
chr(ch)将指定原始值转为字符
去除两端多余字符操作S.lstrip([chars]) -> strReturn a copy of the string S with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.
例1
" myname".lstrip()
⬇
“myname”

例2
“myname”.lstrip(“my”)
⬇
“name”
S.rstrip([chars]) -> strReturn a copy of the string S with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.
S.strip([chars]) -> strReturn a copy of the string S with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.
“!!!my!!!”.strip(“!”)
⬇
“my”
判断开头结尾字符串S.startswith(prefix[, start[, end]]) -> boolReturn 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.
S.endswith(suffix[, start[, end]]) -> boolReturn 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.
字符串计数S.count(sub[, start[, end]]) -> intReturn 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.
len(s) -> intReturn the number of items in a container
编码S.encode(encoding='utf-8', errors='strict') -> bytesEncode S using the codec registered for encoding.

Default encoding is ‘utf-8’. Errors may be given to set a different error handling scheme.

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.
解码bytes.decode(self, /, encoding='utf-8', errors='strict')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.
翻译str.maketrans(x, y=None, z=None, /)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.
table = str.maketrans(‘abc’, ‘123’, ‘none’)
S.translate(table) -> strReturn a copy of the string S in which each character has been mapped through the given translation table.

The table must implement lookup/ indexing via __getitem__, for instance a dictionary or list, mapping Unicode ordinals to Unicode ordinals, strings, or None.

If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
结合上面的table
‘abcd’.translate(table)
⬇
‘123d’

‘none’.translate(table)
⬇
‘’(none映射为空)
转换S.expandtabs(tabsize=8) -> strReturn a copy of S where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.
S.format(*args, **kwargs) -> strReturn a formatted version of S, using substitutions from args and kwargs.

The substitutions are identified by braces (‘{’ and ‘}’).
例子见下面代码
S.format_map(mapping) -> strReturn a formatted version of S, using substitutions from mapping.

The substitutions are identified by braces (‘{’ and ‘}’).
例子见下面代码
  • S.format_map(mapping) -> str
s = 'My name is {name}.'
name = 'xiaoming'
s.format_map(vars())
Out[]: 'My name is xiaoming.'
 
# vars()也能作用在类实例上
class Name:
    def __init__(self, name, n):
        self.name = name
ppl = Name('xiaoming')
s.format_map(vars(ppl))
Out[]: 'My name is xiaoming.'
  • S.format(*args, **kwargs) -> str
'Hello {}'.format('Word')===>Hello Word
-------------------------------------------------
'你喜欢{2}吗?难道你喜欢{1},我猜你喜欢{0}'.format('java','c++','python')
===>你喜欢python吗?难道你喜欢c++,我猜你喜欢java
---------------------------------------------------
name='james'
age=12
'我的名字是{},年龄是{}'.format(name,age)
===>我的名字是james,年龄是12
-----------------------------------------------------
'我的名字是{name},年龄{age}'.format(name='bob',age='30')
===>>我的名字是bob,年龄30
----------------------------------------------------
coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
'Coordinates: {latitude}, {longitude}'.format(**coord)
===>Coordinates: 37.24N, -115.81W
-----------------------------------------------------
'{}-{}-{}'.format(*'abc')==>>a-b-c
-------------------------------------------------
'{:*>10}'.format('love you')
#右对齐默认用空格填充,这个例子设置星号填充
===>>**love you
-------------------------------------------------------
'{:*^30}'.format('centered') 
#居中对齐,默认空格填充,这个例子用性星号填充
===>>>***********centered***********
------------------------------------------------------
'{:*<10}'.format('love you')
#左对齐默认用空格填充,这个例子设置星号填充
=====>>>>love you**
-------------------------------------------------------
'{:.4f}; {:.3f};{:f}'.format(3.14, -3.14,3)
#浮点数保留指定位数小数,未指定则默认六位
===>>>3.1400; -3.140;3.000000
--------------------------------------------------------
"int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
#十进制,16进制,八进制,2进制转换
===>>>int: 42; hex: 2a; oct: 52; bin: 101010 
-------------------------------------------------------
"int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
#加上#好之后
====>>>int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010
--------------------------------------------------------
'{:,}'.format(1234567890)#用逗号作为千位分割符
===》》》1,234,567,890
------------------------------------------------
points=19
total=22
'{:.2%}'.format(19/22)#表示百分数==>>86.36%
-----------------------------------------------------
import datetime
d = datetime.datetime(2010, 7, 4, 12, 15, 58)
st='{:%Y-%m-%d %H:%M:%S}'.format(d)
#格式化时间
==>>>2010-07-04 12:15:58
----------------------------------------------------
octets = [192, 168, 0, 1]
'{:02X}{:02X}{:02X}{:02X}'.format(*octets)
===>>>C0A80001
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/979870.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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