字符串方法(三)

str.isascii 是 ASCII 字符?

字符串方法 str.isascii(),Python 官方文档描述如下:

help(str.isascii)
Help on method_descriptor:

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.

如果字符串为空或字符串中的所有字符都是 ASCII ,返回 True,否则返回 False。ASCII 字符的码点范围是 U+0000-U+007F。

''.isascii()
True
'python'.isascii()
True
'python.3'.isascii()
True
'嗨 python'.isascii()
False

str.isidentifier 是有效标识符?

字符串方法 str.isidentifier(),Python 官方文档描述如下:

help(str.isidentifier)
Help on method_descriptor:

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

如果字符串是有效的标识符,返回 True,否则返回 False。

''.isidentifier()
False
'1mycode'.isidentifier()
False
'_mycode'.isidentifier()
True
'123'.isidentifier()
False
'_123'.isidentifier()
True
'变量名'.isidentifier()
True
'for'.isidentifier()
True

str.isprintable 是可打印字符?

字符串方法 str.isprintable(),Python 官方文档描述如下:

help(str.isprintable)
Help on method_descriptor:

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.

如果字符串中所有字符均为可打印字符或字符串为空则返回 True,否则返回 False。

不可打印字符是在 Unicode 字符数据库中被定义为 ”Other” 或 ”Separator” 的字符,例外情况是 ASCII 空格字符 (0x20) 被视作可打印字符。

请注意在此语境下可打印字符是指当对一个字符串发起调用 repr() 时不必被转义的字符。它们与字符串写入 sys.stdout 或 sys.stderr 时所需的处理无关。

''.isprintable()
True
' '.isprintable()
True
'\n'.isprintable()
False
'\python'.isprintable()
True
'py\thon'.isprintable()
False

str.isspace 是空白字符?

字符串方法 str.isspace(),Python 官方文档描述如下:

help(str.isspace)
Help on method_descriptor:

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.

如果字符串中只有空白字符且至少有一个字符则返回 True,否则返回 False。

''.isspace()
False
' '.isspace()
True
'\n\t\r\f'.isspace()
True
' \\'.isspace()
False

str.removeprefix 移除前缀

字符串方法 str.removeprefix()。

3.9 版本新功能。

str.removeprefix(prefix, /),如果字符串以 前缀字符串 prefix 开头,返回 string[len(prefix):],否则,返回原始字符串的副本。

>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'

str.removesuffix 移除后缀

字符串方法 str.removesuffix()。

3.9 版本新功能。

str.removesuffix(suffix, /),如果字符串以 后缀字符串 suffix 结尾,并且后缀非空,返回 string[:-len(suffix)],否则,返回原始字符串的副本。

>>> 'MiscTests'.removesuffix('Tests')
'Misc'
>>> 'TmpDirMixin'.removesuffix('Tests')
'TmpDirMixin'

猜你喜欢

转载自blog.csdn.net/weixin_46757087/article/details/112853053
今日推荐