Python基础—内置数据类型

一、简介      

       如果你用过C或者C++,你该知道你的许多工作集中在实现数据结构上面。你需要管理内存分配,部署内存结构等等。这些东西比较乏味,通常会让你无法集中在真正想实现的目标上面。

       而在Python中,许多这种乏味的工作都去去除了。Python提供了强大的对象类型作为Python语言的一部分,解决问题时,你不需要手工写代码来实现这些结构了。而且你也不需要亲自实现自己的数据类型。因为内置对象类型有很多好处。如果你是一个编程大牛,哪另当别论,对于初学者,我们首先需要知道如何使用。

 

Python内置数据类型:可以使用dir()查看数据类型支持的属性和方法

       Numbers     

       Strings

       Lists

       Dictionaries

       Tuples

       Files

       Other types   Sets,type,None,Boolean

二、Numbers

支持的number类型

Literal                                 Interpretion                            |                   

1234,-24,0                           Normal intergers(C lons)

999999999999L                   Long intergers(unlimited size)

1.23,3.14e-10,4E210            Floating-point numbers(C doubles)

0177,0x9ff,0xff                    Octal and hex literals for intergers

3+4j,3.0+4.0j,3J                   Comples number literals

Python expression operators and precedure

Operators                                   Description                                               |

yield x                                       Generator function send protocol

lambda args:expression            Anonymous function generation

x if y else z                                 Ternary(三元的) selection expression

x or y                                         Logical OR (X 为假才比较Y)

x and y                                       Logical AND (X 为真才比较Y)

not x                                          Logical negation

<,<=,>,>=,==,!=,x is y,x is not y,x not in y

x | y                                            按位或

x ^ y                                          按位异或

x & y                                          按位与

x << y, x>>y                              按位左移,右移

-x + y, x – y                                加、减

x * y, x % y, x /y, x // y               乘除

-x ,+x, ~x, x ** y

#一些操作
In [1]: 01,010,0100
Out[1]: (1, 8, 64)
 
In [2]: 0x01,0x10,0xff
Out[2]: (1, 16, 255)
 
In [3]: oct(64),hex(64),hex(255)
Out[3]: ('0100', '0x40', '0xff')
              
In [4]: int('0100'),int('0100',8),int('0x40',16)
Out[4]: (100, 64, 64)

关于number方面,math模块有许多处理的函数。

三、Strings

1String也叫seqeunce,字符串在Python中很容易使用,但是最复杂的地方可能在于有很多种方式编写字符串

Single: quotes   :   'spa"m'

Double quotes    :   "spa'm"

Triple quotes    :   """…pam…"",'''…spam…'''

Escape sequence  :   "S\tp\na\Om"

Raw strings      :   r"C:\new\test.spm"

Unicode strings  :   u"eggs\u0020spam"

2、转义字符

Escape Sequence 

Meaning 

\newline

Ignored

\\

Backslash (\)

\'

Single quote (')

\"

Double quote (")

\a

ASCII Bell (BEL)

\b

ASCII Backspace (BS)

\f

ASCII Formfeed (FF)

\n

ASCII Linefeed (LF)

\r

ASCII Carriage Return (CR)

\t

ASCII Horizontal Tab (TAB)

\v

ASCII Vertical Tab (VT)

\ooo

ASCII character with octal value ooo

\xhh…

ASCII character with hex value hh…

3、基础操作

In [1]: a = 'abc'
 
In [2]: 'abc' + 'def'
Out[2]: 'abcdef'
 
In [3]: 'abc' * 3
Out[3]: 'abcabcabc'
 
In [5]: a[1]
Out[5]: 'b'
 
In [6]: a[1:2]
Out[6]: 'b'
 
In [7]: a[1:3]
Out[7]: 'bc'
 
In [8]: a[-1]
Out[8]: 'c'
 
In [9]: a[::2]
Out[9]: 'ac'

4、格式化字符串

In [10]: "%d %s %d you" % (1,'spam',4)

Out[10]: '1 spam 4 you'

Format   Symbol

Conversion

%c

character

%s

string   conversion via str() prior to formatting

%i

signed   decimal integer

%d

signed   decimal integer

%u

unsigned   decimal integer

%o

octal   integer

%x

hexadecimal   integer (lowercase letters)

%X

hexadecimal   integer (UPPERcase letters)

%e

exponential   notation (with lowercase 'e')

%E

exponential   notation (with UPPERcase 'E')

%f

floating   point real number

%g

the   shorter of %f and %e

%G

the   shorter of %f and %E

 

5、字符串的方法 

 'capitalize',                  #首字母大写
 'center',                       # S.center(width[, fillchar]) -> string
 'count',                        # S.count(sub[, start[, end]]) -> int
 'decode',                      #解码
 'encode',                      #编码
 'endswith',                   #以什么结束
 'expandtabs',                # S.expandtabs([tabsize]) -> string #把制表符换为多少字符
 'find',                          # S.find(sub [,start [,end]]) -> int
 'format',                      # 参考:http://blog.csdn.net/handsomekang/article/details/9183303
 'index',                        #和find功能一样,只不过找不到会报错
 'isalnum',                    #是否为数字,字母组成
 'isalpha',                      #是否为字母
 'isdigit',                    #是否为数字
 'islower',                     #是否为小写
 'isspace',                      #是否为空格符
 'istitle',                        #是否为标题样式,即每个单词首字母大写
 'isupper',                     #是否为大写
 'join',                          # In [33]: a = "yunzhonghe"; b = " ";b.join(a) ;Out:'y u n z h o n g h e'
 'ljust',                         # S.ljust(width[, fillchar]) -> string  在右边加空格
 'lower',                       #转变字符串为小写
 'lstrip',                        #去掉左边的空格
 'partition',                   #S.partition(sep) -> (head, sep, tail)  ,分成三段 
 'replace',                            # S.replace(old, new[, count]) -> string
 'rfind',                        #从后面往前找,功能和find一样
 'rindex',                      #同上,找不到会报错
 'rjust',                         #在左边加空格    
 'rpartition',                  #从后往前找
 'rsplit',                        # S.rsplit([sep [,maxsplit]]) -> list of strings
 'rstrip',                        #限制右边的空格
 'split',                         # S.split([sep [,maxsplit]]) -> list of strings 以谁为分隔符
 'splitlines',                   #返回行的列表
 'startswith',                  #以谁开始
 'strip',                         #去除两边的空格符
 'swapcase',                   #大写小互换
 'title',                          #转换为Title 样式
 'translate',                    # S.translate(table [,deletechars]) -> string
 'upper',                       #转换为大写
 'zfill'                           #以 0 填充字符In [58]: a.zfill(10);Out[58]: '0000000abc'

四、Lists

Lists是:有序的对象收集,通过偏移量访问,可变长度,自由嵌套,改变sequence

1、基础操作

In [1]: l = ["abc",'def','ghi']
 
In [2]: l*3
Out[2]: ['abc', 'def', 'ghi', 'abc', 'def', 'ghi', 'abc', 'def', 'ghi']
 
In [3]: [l] * 3
Out[3]: [['abc', 'def', 'ghi'], ['abc', 'def', 'ghi'], ['abc', 'def', 'ghi']]
 
In [4]: l + ["xyz"]
Out[4]: ['abc', 'def', 'ghi', 'xyz']
 
In [5]: l[1]
Out[5]: 'def'
 
In [6]: l[1][1]
Out[6]: 'e'
 
In [7]: l[0:2]
Out[7]: ['abc', 'def']
 
In [8]: l1 = [x**2 for x in range(5)]
 
In [9]: l1
Out[9]: [0, 1, 4, 9, 16]

2List 方法

 'append',                   #添加一个元素
 'count',                        #计算某元素出现次数
 'extend',                      #添加大量元素
 'index',                        # L.index(value, [start, [stop]]) -> integer -- return first index of value.
 'insert',                        # L.insert(index, object) -- insert object before index
 'pop',                          #取出某个数据
 'remove',                     #删除某个数据
 'reverse',                            #顺序翻转
 'sort'                           #整理顺序

五、Dictionaries

Dictionaries也是非常灵活的内置数据类型,列表可以看做有序的对象收集器,Dictionary则是无序的收集。item通过key取出,而不是通过偏移量。

In [19]: dir(dict)
Out[19]:
 '__class__',
 '__cmp__',
 '__contains__',
 '__delattr__',               #删除attr
 '__delitem__',              #删除item
 '__doc__',                   #注释文档信息
 '__eq__',                     #等于
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',               #大于
 '__hash__',
 '__init__',
 '__iter__',
 '__le__',       #小于等于
 '__len__',             #key的个数
 '__lt__',               #小于
 '__ne__',              #不等于
 '__new__',            #
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'clear',                         #清空字典
 'copy',                         # D.copy() -> a shallow copy of D
 'fromkeys',           # In [11]: dict.fromkeys("yun","test")Out[11]: {'n': 'test', 'u': 'test', 'y': 'test'}
 'get',                           # D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
 'has_key',                    # D.has_key(k) -> True if D has a key k, else False
 'items',                        # D.items() -> list of D's (key, value) pairs, as 2-tuples
 'iteritems',                   # D.iteritems() -> an iterator over the (key, value) items of D
 'iterkeys',                    #
 'itervalues',                  #
 'keys',                         # D.keys() -> list of D's keys
 'pop',                   # D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
 'popitem',                    #随意取一些key-item 数据
 'setdefault',                  # D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
 'update',                      #
                            D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
                            If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
                            If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
                            In either case, this is followed by: for k in F: D[k] = F[k]
 'values',                # D.values() -> list of D's values
 'viewitems',          #
              #In [30]: a.viewitems()
              #Out[30]: dict_items([('age', 19), ('name', 'yunzhonghe'), ('school', 'hqu')])
 'viewkeys',
 'viewvalues'

 

六、Tuples

TupleList类似,都是类型收集,但是Tuple不能按位修改。

Tuple的特点:有序的收集任意对象,通过偏移量访问,不可变sequence,固定长度,自由嵌套。

In [39]: dir(tuple)
Out[39]:
['__add__',                           #可以和Tuple相加
 '__class__',
 '__contains__',
 '__delattr__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__getslice__',
 '__gt__',
 '__hash__',
 '__init__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',    
 '__rmul__',
 '__setattr__',               
 '__sizeof__',                       #占用内存的大小
 '__str__',                            #可以调用str 方法
 '__subclasshook__',
 'count',                               #计算某个value出现多少次
 'index']                              #查看某value的index

七、Files

文件是一个命名的隔离存储空间,被操作系统管理。
fp = open("test.txt",w)     直接打开一个文件,如果文件不存在则创建文件

 

1open 模式:

w     以写方式打开,
a     以追加模式打开 (从 EOF 开始, 必要时创建新文件)
r+     以读写模式打开
w+     以读写模式打开 (参见 w )
a+     以读写模式打开 (参见 a )
rb     以二进制读模式打开
wb     以二进制写模式打开 (参见 w )
ab     以二进制追加模式打开 (参见 a )
rb+    以二进制读写模式打开 (参见 r+ )
wb+    以二进制读写模式打开 (参见 w+ )
ab+    以二进制读写模式打开 (参见 a+ )

 

2、文件方法

fp.read([size])                     #size为读取的长度,以byte为单位
fp.readline([size])                 #读一行,如果定义了size,有可能返回的只是一行的一部分
fp.readlines([size])                #把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长,也就是说可能只读到文件的一部分。
fp.write(str)                        #把str写到文件中,write()并不会在str后加上一个换行符
fp.writelines(seq)                   #把seq的内容全部写到文件中(多行一次性写入)。这个函数也只是忠实地写入,不会在每行后面加上任何东西。
fp.close()                           #关闭文件。python会在一个文件不用后自动关闭文件,不过这一功能没有保证,最好还是养成自己关闭的习惯。  如果一个文件在关闭后还对其进行操作会产生ValueError
fp.flush()                            #把缓冲区的内容写入硬盘
fp.fileno()                           #返回一个长整型的”文件标签“
fp.isatty()                           #文件是否是一个终端设备文件(unix系统中的)
fp.tell()                             #返回文件操作标记的当前位置,以文件的开头为原点
fp.next()                             #返回下一行,并将文件操作标记位移到下一行。把一个file用于for … in file这样的语句时,就是调用next()函数来实现遍历的。
fp.seek(offset[,whence])              #将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的,一般为正数。但如果提供了whence参数就不一定 了,whence可以为0表示从头开始计算,1表示以当前位置为原点计算。2表示以文件末尾为原点进行计算。需要注意,如果文件以a或a+的模式打开,每 次进行写操作时,文件操作标记会自动返回到文件末尾。
fp.truncate([size])                  #把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。如果size比文件的大小还要大,依据系统的不同可能是不改变文件,也可能是用0把文件补到相应的大小,也可能是以一些随机的内容加上去。

八、后记

1Python常用基础类型差不多就这么多,供以后参考使用。

2、为什么表格这么大

 

参考:http://www.cnblogs.com/rollenholt/archive/2012/04/23/2466179.html

原创文章,作者:艾贺,如若转载,请注明出处:http://www.178linux.com/9215

(0)
艾贺艾贺
上一篇 2015-11-10 22:36
下一篇 2015-11-10 22:40

相关推荐

  • centos 7 之nmcli命令

    1、nmcli命令的作用 nmcli : command‐line tool for controlling NetworkManager     NetworkManager:动态管理和监控网络设置的守护进程。用户和脚本都可使用命令行工具 nmcl…

    Linux干货 2016-09-10
  • N26-博客作业-week13

    1、建立samba共享,共享目录为/data,要求:(描述完整的过程)  1)共享名为shared,工作组为magedu;  2)添加组develop,添加用户gentoo,centos和ubuntu,其中gentoo和centos以develop为附加组,ubuntu不属于develop组;密码均为用户名;  3)添加samb…

    Linux干货 2017-06-15
  • Linux常用命令

    一、Linux常用命令(总) 二、Linux常用命令(分) 1、pwd – print name of current/working directory 2、cd – change directory 3、ls – list,dieplay directory content 4、date – pr…

    Linux干货 2016-09-19
  • Linux文件压缩、解压、归档总结

    一、简介   压缩对我们来说通常意味着减小文件体积,节省硬盘空间。在Windows平台上处理大文件或目录中的文件很多时我们都需要对这些文件进行压缩处理,压缩格式多种多样,如:zip、rar、7z等格式,压缩方式也比较多样话,支持按最大压缩比例或者最快时间进行压缩等多种方式,而生成的压缩包就可以让我们更方便的进行拷贝及归档整理。解压缩顾名思义就是回归…

    Linux干货 2015-09-26
  • 逻辑卷管理器LVM

    一、LVM逻辑卷管理     lvm(Logical Volume Manage,逻辑卷管理)的重点在于可以弹性的调整filesystem的容量,而并非在于数据的存储效率及安全上面。需要文件的读写效能或者是数据的可靠性是RAID所考虑的问题。LVM可以整合多个实体partition在一起,让这些partitions看起…

    Linux干货 2016-09-02
  • SSH端口转发

      SSH 会自动加密和解密所有SSH 客户端与服务端之间的网络数据。但是,SSH 还能够将其他TCP 端口的网络数据通过SSH 链接来转发,并且自动提供了相应的加密及解密服务。这一过程也被叫做“隧道”(tunneling),这是因为SSH 为其他TCP 链接提供了一个安全的通道来进行传输而得名。例如,Telnet,SMTP,LDAP 这些TCP 应用均能够…

    2017-09-10

评论列表(2条)

  • stanley
    stanley 2015-11-10 22:39

    没有上次提交的文章质量高哦。

    • 云中鹤
      云中鹤 2015-11-11 20:09

      @stanley恩,不光供自己参考,还要让别看看起来好才行。