Python Data Type

Python 数据类型:哈希类型、不可哈希类型

  • 数字类型:int, float, decimal.Decimal, fractions.Fraction, complex
  • 字符串类型:str, bytes
  • 元组:tuple
  • 冻结集合:frozenset
  • 布尔类型:True, False
  • None
  • 哈希类型, 即在原地不能改变的变量类型, 不可变类型。可利用hash函数查看其hash值, 也可以作为字典的key。
  • 不可hash类型:原地可变类型:list 、dict set。它们不可以作为字典的key。

 数字常量

  • 1236, -1236, 0, 999999999          # 整数
  • 1.2, 1. ,3.1415926, 3.14e-10, 4E2, 4.0e+5  # 浮点数
1 >>> 3.14e-10
2 3.14e-10
3 >>> '{:.15f}'.format(3.14e-10)
4 '0.000000000314000'
5 >>> 4E2
6 400.0
7 >>> 4.0e+5
8 400000.0
9 >>> 
  • 0o177    #  八进制(0o开头)
  • 0x9ff      # 十六进制(0x开头)
  • 0b1010  # 二进制数字(0b开头)
1 >>> 0o177        # 1 * 8**2 + 7 * 8**1 + 7 * 8**0  == 127
2 127
3 >>> 0x9ff        # 9 * 16**2 + 15 * 16**1 + 15 * 16**0 == 2559
4 2559
5 >>> 0xFF         # 不区分大小写(A:10, B:11, C:12, D:13, E:14, F:15)
6 255
7 >>> 0b1010       # 1 * 2**3 + 1 * 2**1  == 10
8 10
9 >>> 
  • oct(I)  # 将十进制(decimal )转化成八进制(octal表示的“字符串”
  • hex(I)    # 将十进制(decimal )转化成十六进制(hexadecimal表示的“字符串”
  • bin(I)   # 将十进制(decimal )转化成二进制(binary)表示的“字符串”
1 >>> oct(255)
2 '0o377'
3 >>> hex(255)
4 '0xff'
5 >>> bin(255)
6 '0b11111111'
7 >>> 

int(string, base)  # 将字符串转化成整数, base为字符串所代表的进制数,

             # 可以将表示其他进制的数的字符串转化成十进制的整数

1 >>> int('0o377', base = 8)
2 255
3 >>> int('0xff', base = 16)
4 255
5 >>> int('0b11111111', 2)
6 255
7 >>> 

3+6j, 3.0+6.0j, 3J  # 附属常量, 也可以用 complex(real, image) 来创建

 1 >>> type(3+6j)
 2 <class 'complex'>
 3 >>> type(3.0+6.0j)
 4 <class 'complex'>
 5 >>> type(3J)
 6 <class 'complex'>
 7 >>> 
 8 >>> a = complex(3, 6)
 9 >>> a
10 (3+6j)
11 >>> 

2.x中,有两种整数类型:

  1. 一般整数(32位);
  2. 长整数(无穷精度)。可以用l 或 L 结尾,迫使一般整数成为长整数
 1 >>> a = 2 ** 30
 2 >>> a
 3 1073741824
 4 >>> type(a)
 5 <type 'int'>
 6 >>>
 7 >>> b = 2 ** 31
 8 >>> b
 9 2147483648L
10 >>> type(b)
11 <type 'long'>
12 >>>

整数可以利用 bit_length 函数测试用二进制表示所占的位数:

  a = 1 ;    a.bit_length()    #  1

  b = 2 ;    b.bit_length()    #  2

  c  = 3;    c.bit_length()    #  2

  d = 4;     d.bit_length()    #  3

  e = 1024;    e.bit_length()    #  11

 1 >>> a = 1
 2 >>> a.bit_length()
 3 1
 4 >>> b = 2
 5 >>> b.bit_length()
 6 2
 7 >>> c = 3
 8 >>> c.bit_length()
 9 2
10 >>> d = 4
11 >>> d.bit_length()
12 3
13 >>> e = 1024
14 >>> e.bit_length()
15 11
16 >>> 

 布尔类型 bool : True (真), False(假)

  • int  --->  bool   :   0 ---> False;   非0   ---> True
  • bool  ---> int    :   False  ---> 0;  True  --->  1
1 >>> type(True)            # 返回<class 'bool'>
2 <class 'bool'>
3 >>> type(False)            # 返回<class 'bool'>
4 <class 'bool'>
5 >>> isinstance(False, int) # bool 类型属于整形,所以返回True
6 True
7 >>> True == 1, True is 1   # 输出(True, False)
8 (True, False)
9 >>> 
  • str   --->  bool  :   (Null)     ---> False;        不是Null     ---> True
  • list  --->  bool  :   元素为空 ---> False;       元素不为空 ---> True
 1 >>> a = ''
 2 >>> bool(a)
 3 False
 4 >>> b = 'f'
 5 >>> bool(b)
 6 True
 7 >>> 
 8 >>> lst = []
 9 >>> type(lst)
10 <class 'list'>
11 >>> bool(lst)
12 False
13 >>> lst = ['a']
14 >>> type(lst)
15 <class 'list'>
16 >>> bool(lst)
17 True
18 >>> 

常见字符串常量和表达式

  • S1 = ''             # 空字符串
  • S2 = "Today's good day"  # 双引号和单引号同时使用
  • S3 = "s p a x00 m"     # 转义字符
  • S4 = '''docment'''       # 三重引号字符串,一般用于函数说明
  • S5 = r' emp'         # Raw字符串,不会进行转义,抑制转义
  • S6 = b'101100'         # Python3中的字节字符串
  • S7 = u'0x4EFA'          # Python2.x 中的Unicode字符串
 1 >>> S1 = ''                    # 空字符串
 2 >>> S2 = "Today's good day"    # 双引号和单引号同时使用
 3 >>> S3 = "s
 p 	 a x00 m"   # 转义字符
 4 >>> S4 = '''document'''        # 三重引号字符串,一般用于函数说明
 5 >>> S5 = r'	emp'              # Raw字符串,不会进行转义,抑制转义
 6 >>> S6 = b'101100'             # Python3中的字节字符串
 7 >>> print(S1, type(S1))
 8  <class 'str'>
 9 >>> print(S2, type(S2))
10 Today's good day <class 'str'>
11 >>> print(S3, type(S3))
12 s
13  p      a   m <class 'str'>
14 >>> print(S4, type(S4))
15 document <class 'str'>
16 >>> print(S5, type(S5))
17 	emp <class 'str'>
18 >>> print(S6, type(S6))
19 b'101100' <class 'bytes'>
20 >>> 
1 >>> S7 = u'0x4EFA'               # Python2.6中的Unicode字符串
2 >>> print(S7, type(S7))
3 (u'0x4EFA', <type 'unicode'>)
4 >>>
1 >>> S7 = u'0x4EFA'
2 >>> print(S7, type(S7))
3 0x4EFA <class 'str'>
4 >>> 
  • S2[1], S2[-1], S2[:3], len(S2)      # 字符串操作
  • 'a %s parrot' % 'kind'          # 字符串格式化表达式
  • 'a {1} {0} parrot'.format('kind', 'red')    # 字符串格式化方法
1 >>> S2[1], S2[-1], S2[:3], len(S2)
2 ('o', 'y', 'Tod', 16)
3 >>> print('a %s parrot' % 'kind')
4 a kind parrot
5 >>> print('a {1} {0} parrot'.format('kind', 'red') )
6 a red kind parrot
7 >>> 

内置str处理函数:

  • 对于不变对象来说,调用对象自身的任意方法,也不会改变该对象自身的内容。
  • 相反,这些方法会创建新的对象并返回,这样,就保证了不可变对象本身永远是不可变的
  1. upper();   lower();  # 全部大写,全部小写
  2. swapcase();           # 大小写转换
  3. capitalize();  title()  # 每个单词的首字母都大写
 1 >>> str1 = "stringOfobjectTest"
 2 >>> str1.upper()
 3 'STRINGOFOBJECTTEST'
 4 >>> str1.lower()
 5 'stringofobjecttest'
 6 >>> str1.swapcase()
 7 'STRINGoFOBJECTtEST'
 8 >>> str1.capitalize()
 9 'Stringofobjecttest'
10 >>> "LIFE IS SHORT, USE PYTHON".title()
11 'Life Is Short, Use Python'
12 >>>
  1. ljust(width)          # 获取固定长度,左对齐,右边不够用空格补齐
  2. rjust(width)          # 获取固定长度,右对齐,左边不够用空格补齐
  3. center(width[,'*'])      # 获取固定长度,中间对齐,两边不够用空格补齐,可指定填充字符
  4. zfill(width)                 # 获取固定长度,右对齐,左边不足用0补齐
 1 >>> "infor".ljust(20)        # 获取固定长度,左对齐,右边不够用空格补齐
 2 'infor               '
 3 >>> "infor".rjust(20)        # 获取固定长度,右对齐,左边不够用空格补齐
 4 '               infor'
 5 >>> "infor".center(20)       # 获取固定长度,中间对齐,两边不够用空格补齐
 6 '       infor        '
 7 >>> "infor".center(20, '*')  # 可指定填充字符
 8 '*******infor********'
 9 >>> "682.6".zfill(20)        # 获取固定长度,右对齐,左边不足用0补齐
10 '000000000000000682.6'
11 >>> 
  1. find('a',start,end)      # 查找字符串,可以指定起始及结束位置搜索
  2. rfind('a')                     # 从右边开始查找字符串
  3. index('a',start,end)   # 使用index查找不到会抛异常,而find返回-1
  4. count('a')                   # 查找字符串出现的次数
 1 >>> S2
 2 "Today's good day"
 3 >>> S2.find('a')           # 查找字符串,可以指定起始及结束位置搜索
 4 3
 5 >>> S2.find('a', 4, -1)    # 查找字符串,可以指定起始及结束位置搜索
 6 14
 7 >>> S2.rfind('a')          # 从右边开始查找字符串
 8 14
 9 >>> S2.index('a', 4)       # 查找字符串,可以指定起始及结束位置搜索
10 14
11 >>> S2.count('a')          # 查找字符串出现的次数
12 2
13 >>> S2.find('n')           # 找不到,find返回-1
14 -1
15 >>> S2.index('n')          # 使用index查找不到会抛异常,而find返回-1
16 Traceback (most recent call last):
17   File "<pyshell#62>", line 1, in <module>
18     S2.index('n')
19 ValueError: substring not found
20 >>> 
  1. replace('old','new')     # 替换函数,替换old为new,参数中可以指定maxReplaceTimes,即替换指定次数的old为new
  2. strip();                          # 默认删除空白符
  3. strip('d');                      # 删除Str1字符串中开头、结尾处,位于 d 删除序列的字符
  4. lstrip();
  5. lstrip('d');                     # 删除Str1字符串中开头处,位于 d 删除序列的字符
  6. rstrip();
  7. rstrip('d')                      # 删除Str1字符串中结尾处,位于 d 删除序列的字符
 1 >>> Str1 = '  --- we all like beautiful woman woman woman. ***   '
 2 >>> Str1.replace('woman', 'girl')
 3 '  --- we all like beautiful girl girl girl. ***   '
 4 >>> Str1.replace('woman', 'girl', 2)
 5 '  --- we all like beautiful girl girl woman. ***   '
 6 >>> Str1.lstrip()
 7 '--- we all like beautiful woman woman woman. ***   '
 8 >>> Str1.lstrip(' -')
 9 'we all like beautiful woman woman woman. ***   '
10 >>> Str1.rstrip()
11 '  --- we all like beautiful woman woman woman. ***'
12 >>> Str1.rstrip(' *')
13 '  --- we all like beautiful woman woman woman.'
14 >>> Str1.strip()
15 '--- we all like beautiful woman woman woman. ***'
16 >>> Str1.strip(' -*')
17 'we all like beautiful woman woman woman.'
18 >>> 
  1. str1.startswith('start')          # 是否以start开头
  2. str1.endswith('end')          # 是否以end结尾
  3. str1.isalnum();             # 判断字符串是否全为字符和数字
  4. str1.isalpha();  str1.isdigit();       # 判断字符串是否全为字符、数字
  5. str1.islower();  str1.isupper()      # 判断字符串是否全为小写、大写
 1 >>> str1 = "A red-black tree is a binary search tree with one extra bit of storage per node: it's color, which can be either RED or BLACK."
 2 >>> str1.startswith('A red-black tree')
 3 True
 4 >>> str1.endswith('BLACK')
 5 False
 6 >>> str1.isalnum()
 7 False
 8 >>> str1.isalpha()
 9 False
10 >>> str1.isdigit()
11 False
12 >>> str1.islower()
13 False
14 >>> str1.isupper()
15 False
16 >>> 'Ared-blacktreeisabinarysearchtree666'.isalnum()
17 False
18 >>> 'Aredblacktreeisabinarysearchtree666'.isalnum()
19 True
20 >>> 'Aredblacktreeisabinarysearchtree'.isalpha()
21 True
22 >>> '123456  '.isdigit()
23 False
24 >>> '123456'.isdigit()
25 True
26 >>> 'AREDBLACKTREEISABINARYSEARCHTREE'.isupper()
27 True
28 >>> 'aredblacktreeisabinarysearchtree'.islower()
29 True
30 >>>
原文地址:https://www.cnblogs.com/51try-again/p/10160044.html