python isdigit什么意思_讨论 - 廖雪峰的官方网站

如果还没有消气。再来一个Python3的内建类型提要,这个很基础很重要的:

Python36 内建类型

主要的内建类型有数字,序列,映射,类,实例和异常。

4.4 数字类型 -- int,float,complex

4.6 序列类型 -- list,tuple,range

immutable 不可改变的;

mutable 可改变的;

class list([iterable])

class tuple([iterable])

class range(stop)

class range(start, stop[, step])

4.7 文本序列类型 — str

class str(object='')

class str(object=b'', encoding='utf-8', errors='strict')

4.7.1 字符串方法

casefolded 大小写折叠

str.capitalize() 首字符大写,其它小写。

str.casefold() 返回字符串拷贝的小写字符串

str.center(width[, fillchar]) 返回固定宽度的字符串

str.count(sub[, start[, end]]) 返回子串的个数

str.encode(encoding="utf-8", errors="strict") 编码字符串

str.endswith(suffix[, start[, end]]) 判断结尾字符

str.expandtabs(tabsize=8) 返回字符串的一个拷贝,tab使用空格替换

str.find(sub[, start[, end]]) 返回查到的子串的索引

str.format(args, *kwargs) 执行字符串的格式操作

字符串包含文本或者替代字段用大括号{}括起来

每个替换字段包含位置参数的索引,或者关键字参数的名称

str.format_map(mapping) 类似于str.format(**mapping)

str.index(sub[, start[, end]])

str.isalnum()

str.isalpha()

str.isdecimal()

str.isdigit()

str.isidentifier()

str.islower()

str.isnumeric()

str.isprintable()

str.isspace()

str.istitle() 首字母大写时为True

str.isupper() 都是大写字母时为True

str.join(iterable)

str.ljust(width[, fillchar])

str.lower()

str.lstrip([chars])

static str.maketrans(x[, y[, z]])

print(str.maketrans('abc','www','d'))

{97: 119, 98: 119, 99: 119, 100: None}

str.partition(sep) 返回分隔器前的部分,分隔器,分隔器后的部分

str.replace(old, new[, count])

str.rfind(sub[, start[, end]]) 返回子串出现的最大索引

str.rindex(sub[, start[, end]]) 同rfind

str.rjust(width[, fillchar])

str.rpartition(sep)

str.rsplit(sep=None, maxsplit=-1)

str.rstrip([chars])

str.split(sep=None, maxsplit=-1)

str.splitlines([keepends])

str.startswith(prefix[, start[, end]])

str.strip([chars])

str.swapcase()

str.title()

>>> 'Hello world'.title()

'Hello World'

str.translate(table)

str.upper()

str.zfill(width)

4.7.2. printf-style String Formatting

>>> print('%(language)s has %(number)03d quote types.' %

... {'language': "Python", "number": 2})

Python has 002 quote types.

4.8 Binary Sequence Types — bytes, bytearray, memoryview

4.8.1 bytes

bytes 类似字符串,不同的是前面加了一个b

r前缀禁止转义。

除了文字格式,bytes对象还可以由其它方法创建。

指定长度的零填充的bytes对象: bytes(10)

来自可迭代的整数: bytes(range(20))

通过缓冲协议拷贝存在的二进制数据: bytes(obj)

classmethod bytes.fromhex(string)

>>> bytes.fromhex('2Ef0 F1f2 ')

b'.\xf0\xf1\xf2'

bytes.hex()

>>> b'\xf0\xf1\xf2'.hex()

'f0f1f2'

4.8.2 bytearray

创建一个空实例: bytearray()

创建一个给定长度的零填充的实例: bytearray(10)

来自整数的一个迭代: bytearray(range(20))

通过缓存协议拷贝存在的二进制数据: bytearray(b'Hi!')

classmethod bytearray.fromhex(string)

>>> bytearray.fromhex('2Ef0 F1f2 ')

bytearray(b'.\xf0\xf1\xf2')

bytearray.hex()

>>> bytearray(b'\xf0\xf1\xf2').hex()

'f0f1f2'

4.8.3 Bytes和Bytearray的操作

bytes.count(sub[, start[, end]])

bytearray.count(sub[, start[, end]])

bytes.decode(encoding="utf-8", errors="strict")

bytearray.decode(encoding="utf-8", errors="strict")

bytes.endswith(suffix[, start[, end]])

bytearray.endswith(suffix[, start[, end]])

bytes.find(sub[, start[, end]])

bytearray.find(sub[, start[, end]])

bytes.index(sub[, start[, end]])

bytearray.index(sub[, start[, end]])

bytes.join(iterable)

bytearray.join(iterable)

static bytes.maketrans(from, to)

static bytearray.maketrans(from, to)

bytes.partition(sep)

bytearray.partition(sep)

bytes.replace(old, new[, count])

bytearray.replace(old, new[, count])

bytes.rfind(sub[, start[, end]])

bytearray.rfind(sub[, start[, end]])

bytes.rindex(sub[, start[, end]])

bytearray.rindex(sub[, start[, end]])

bytes.rpartition(sep)

bytearray.rpartition(sep)

bytes.startswith(prefix[, start[, end]])

bytearray.startswith(prefix[, start[, end]])

bytes.translate(table[, delete])

bytearray.translate(table[, delete])

bytes.center(width[, fillbyte])

bytearray.center(width[, fillbyte])

bytes.ljust(width[, fillbyte])

bytearray.ljust(width[, fillbyte])

bytes.lstrip([chars])

bytearray.lstrip([chars])

bytes.rjust(width[, fillbyte])

bytearray.rjust(width[, fillbyte])

bytes.rsplit(sep=None, maxsplit=-1)

bytearray.rsplit(sep=None, maxsplit=-1)

bytes.rstrip([chars])

bytearray.rstrip([chars])

bytes.split(sep=None, maxsplit=-1)

bytearray.split(sep=None, maxsplit=-1)

bytes.strip([chars])

bytearray.strip([chars])

bytes.capitalize()

bytearray.capitalize()

bytes.expandtabs(tabsize=8)

bytearray.expandtabs(tabsize=8)

bytes.isalnum()

bytearray.isalnum()

bytes.isalpha()

bytearray.isalpha()

bytes.isdigit()

bytearray.isdigit()

bytes.islower()

bytearray.islower()

bytes.isspace()

bytearray.isspace()

bytes.istitle()

bytearray.istitle()

bytes.isupper()

bytearray.isupper()

bytes.lower()

bytearray.lower()

bytes.splitlines(keepends=False)

bytearray.splitlines(keepends=False)

bytes.swapcase()

bytearray.swapcase()

bytes.title()

bytearray.title()

bytes.upper()

bytearray.upper()

bytes.zfill(width)

bytearray.zfill(width)

4.8.4 printf-style Bytes Formatting

>>> print(b'%(language)s has %(number)03d quote types.' %

... {b'language': b"Python", b"number": 2})

b'Python has 002 quote types.'

4.8.5 memoryview

class memoryview(obj)

>>> v = memoryview(b'abcefg')

>>> v[1]

98

>>> v[-1]

103

>>> v[1:4]

>>> bytes(v[1:4])

b'bce'

>>> data = bytearray(b'abcefg')

>>> v = memoryview(data)

>>> v.readonly

False

>>> v[0] = ord(b'z')

>>> data

bytearray(b'zbcefg')

>>> v[1:4] = b'123'

>>> data

bytearray(b'z123fg')

>>> v[2:3] = b'spam'

Traceback (most recent call last):

File "", line 1, in

ValueError: memoryview assignment: lvalue and rvalue have different structures

>>> v[2:6] = b'spam'

>>> data

bytearray(b'z1spam')

memoryview 有几个方法:

eq(exporter)

tobytes()

>>> m = memoryview(b"abc")

>>> m.tobytes()

b'abc'

>>> bytes(m)

b'abc'

hex()

>>> m = memoryview(b"abc")

>>> m.hex()

'616263'

tolist()

>>> memoryview(b'abc').tolist()

[97, 98, 99]

>>> import array

>>> a = array.array('d', [1.1, 2.2, 3.3])

>>> m = memoryview(a)

>>> m.tolist()

[1.1, 2.2, 3.3]

release()

>>> m = memoryview(b'abc')

>>> m.release()

>>> m[0]

Traceback (most recent call last):

File "", line 1, in

ValueError: operation forbidden on released memoryview object

>>> with memoryview(b'abc') as m:

... m[0]

...

97

>>> m[0]

Traceback (most recent call last):

File "", line 1, in

ValueError: operation forbidden on released memoryview object

cast(format[, shape])

>>> import array

>>> a = array.array('l', [1,2,3])

>>> x = memoryview(a)

>>> x.format

'l'

>>> x.itemsize

8

>>> len(x)

3

>>> x.nbytes

24

>>> y = x.cast('B')

>>> y.format

'B'

>>> y.itemsize

1

>>> len(y)

24

>>> y.nbytes

24

>>> b = bytearray(b'zyz')

>>> x = memoryview(b)

>>> x[0] = b'a'

Traceback (most recent call last):

File "", line 1, in

ValueError: memoryview: invalid value for format "B"

>>> y = x.cast('c')

>>> y[0] = b'a'

>>> b

bytearray(b'ayz')

>>> import struct

>>> buf = struct.pack("i"*12, *list(range(12)))

>>> x = memoryview(buf)

>>> y = x.cast('i', shape=[2,2,3])

>>> y.tolist()

[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]

>>> y.format

'i'

>>> y.itemsize

4

>>> len(y)

2

>>> y.nbytes

48

>>> z = y.cast('b')

>>> z.format

'b'

>>> z.itemsize

1

>>> len(z)

48

>>> z.nbytes

48

>>> buf = struct.pack("L"*6, *list(range(6)))

>>> x = memoryview(buf)

>>> y = x.cast('L', shape=[2,3])

>>> len(y)

2

>>> y.nbytes

48

>>> y.tolist()

[[0, 1, 2], [3, 4, 5]]

obj

>>> b = bytearray(b'xyz')

>>> m = memoryview(b)

>>> m.obj is b

True

nbytes

>>> import array

>>> a = array.array('i', [1,2,3,4,5])

>>> m = memoryview(a)

>>> len(m)

5

>>> m.nbytes

20

>>> y = m[::2]

>>> len(y)

3

>>> y.nbytes

12

>>> len(y.tobytes())

12

>>> import struct

>>> buf = struct.pack("d"*12, *[1.5*x for x in range(12)])

>>> x = memoryview(buf)

>>> y = x.cast('d', shape=[3,4])

>>> y.tolist()

[[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]]

>>> len(y)

3

>>> y.nbytes

96

readonly

format

memoryview(b'abc')[0] == b'abc'[0] == 97.

itemsize

>>> import array, struct

>>> m = memoryview(array.array('H', [32000, 32001, 32002]))

>>> m.itemsize

2

>>> m[0]

32000

>>> struct.calcsize('H') == m.itemsize

True

ndim

shape

strides

suboffsets

c_contiguous

f_contiguous

contiguous

4.9 Set Types — set, frozenset

class set([iterable])

class frozenset([iterable])

4.10 Mapping Types — dict

class dict(kwarg)

class dict(mapping,kwarg)

class dict(iterable, **kwarg)

If a subclass of dict defines a method missing() and key is not present,

the d[key] operation calls that method with the key key as argument.

The d[key] operation then returns or raises whatever is returned

or raised by the missing(key) call.

No other operations or methods invoke missing().

If missing() is not defined, KeyError is raised.

missing() must be a method; it cannot be an instance variable:

>>> class Counter(dict):

... def __missing__(self, key):

... return 0

>>> c = Counter()

>>> c['red']

0

>>> c['red'] += 1

>>> c['red']

1

4.10.1. Dictionary view objects

>>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}

>>> keys = dishes.keys()

>>> values = dishes.values()

>>> # iteration

>>> n = 0

>>> for val in values:

... n += val

>>> print(n)

504

>>> # keys and values are iterated over in the same order

>>> list(keys)

['eggs', 'bacon', 'sausage', 'spam']

>>> list(values)

[2, 1, 1, 500]

>>> # view objects are dynamic and reflect dict changes

>>> del dishes['eggs']

>>> del dishes['sausage']

>>> list(keys)

['spam', 'bacon']

>>> # set operations

>>> keys & {'eggs', 'bacon', 'salad'}

{'bacon'}

>>> keys ^ {'sausage', 'juice'}

{'juice', 'sausage', 'bacon', 'spam'}

4.11 Context Manager Types

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值