python --- 字符串、数据类型、格式化、文件打开

来源:互联网 发布:python simyou 编辑:程序博客网 时间:2024/06/11 06:37

python — 字符串、数据类型、格式化、文件打开

#一、类型#1、不可以变的数据类型string , int , tuple(元组)>>> a = 'test'#不可以变数据>>> a[0] = 'r'Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: 'str' object does not support item assignment>>> a[0] = rTraceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: 'str' object does not support item assignment>>> print a[0]t>>> >>> b = [1,2,3,4,5]#可变数据>>> print b[0]1>>> b[0] = 8>>> b[8, 2, 3, 4, 5]>>> 字符串不可变之在深究>>> c = 'myiswang'字符串其实也是一个序列,并且该序列是无法变更的#2、可变的数据类型 变量dict , list#二、再究字符串序列到底是什么#1、三个符号的区别'',"",""" """当中的''与""没有任何区别的,使用\转义字符可以原样输出>>> d = 'abcdef'>>> d = "abcdef">>> e = "abcdef">>> print dabcdef>>> print eabcdef>>> e = "a'bcdef">>> f = "a'bcdef">>> g = "a'bcdef'">>> print fa'bcdef>>> print ga'bcdef'>>> h = 'a\'bcdef'>>> print ha'bcdef>>> h = "a\"bcdef">>> i = "a\"bcdef">>> print ia"bcdef>>> #""" """是多行注释使用,注释使用格式>>> >>> print """...     my name is lilei ...     haha... """    my name is lilei     haha>>> >>> print """...     test is test ...     yes it is...     'are you sure'...     "i sure !!"...     start test""...     no start ''...     """    test is test     yes it is    'are you sure'    "i sure !!"    start test""    no start ''>>> #2、偏移量从0开始#3、如何修改字符串之replace,find#对字符串修改,其实是重新赋值到一个新的字符串中,那是因为字符串是不可变的数据导致的。谨记,要重新赋值给的新的字符串>>> a = 'this is world!!'>>> a.replace('this','it')'it is world!!'>>> a#显示a字符串,还是原样'this is world!!'>>> b = a.replace('this','it')#赋值给一个新的字符串>>> b'it is world!!'>>> a = a.replace('this','it')#也可以给a重新赋值>>> a'it is world!!'>>> #查询字符串find>>> c = 'that is world!!'>>> c.find('is')5>>> c.find('t')0>>> c.find('that')0>>> c.find('world')8>>> c.find('w')8>>> c[8:]'world!!'>>> d = 'world that is world ,very world!!!world is world!!'>>> d.find('wolrd')#不存在的字符,就显示-1-1>>> d.find('world')0>>> help(d.find)>>> Help on built-in function find:find(...)    S.find(sub [,start [,end]]) -> int    Return 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.(END)#查询is后面的world字符是几位开始的>>> >>> d.find('is')11>>> d.find('world',11)14>>> #三、格式化细究#1、%格式化方式#有两个%s,按照顺序进行格式化读取,不可以更换读取字符串顺序root@72132server:~/python/laowangpy# lsgeshihua.py  hello.py  _projectroot@72132server:~/python/laowangpy# cat geshihua.py #!/usr/bin/pyton# --*-- coding:utf-8 --*--#%d 表示格式化数字  %s 表示格式化字符串a = "this is a %s" % 'apple'b = "this is a %s" % 4c = "this is a %s or %s " % (4,10)d = "this is a %s or %s " % ("apple","car")print aprint bprint cprint droot@72132server:~/python/laowangpy# python geshihua.py this is a applethis is a 4this is a 4 or 10 this is a apple or car root@72132server:~/python/laowangpy# #2、format格式化方式(强烈推荐格式化的该方法)#format可以更改格式化输出的字符串的顺序,{1}表示显示第二个字符串,{0}表示显示第一个字符串root@72132server:~/python/laowangpy# cat geshihua.py #!/usr/bin/pyton# --*-- coding:utf-8 --*--#%d 表示格式化数字  %s 表示格式化字符串a = "this is a %s" % 'apple'b = "this is a %s" % 4#%s是根据顺序完成输出字符串的,是不可以更改顺序的c = "this is a %s or %s " % (4,10)d = "this is a %s or %s " % ("apple","car")#format最基础的用法e = "this is a {} or {} " .format ("apple","car")#format可以更改要输出的字符串的顺序,{1}表示显示第二个字符串,{0}表示显示第一个字符串f = "this is a {1} or {0} " .format ("apple","car")print aprint bprint cprint dprint eprint froot@72132server:~/python/laowangpy# python geshihua.py this is a applethis is a 4this is a 4 or 10 this is a apple or car this is a apple or car this is a car or apple root@72132server:~/python/laowangpy# #format高级的用法root@72132server:~/python/laowangpy# cat geshihua.py #!/usr/bin/pyton# --*-- coding:utf-8 --*--#%d 表示格式化数字  %s 表示格式化字符串a = "this is a %s" % 'apple'b = "this is a %s" % 4#%s是根据顺序完成输出字符串的,是不可以更改顺序的c = "this is a %s or %s " % (4,10)d = "this is a %s or %s " % ("apple","car")#format最基础的用法e = "this is a {} or {} " .format ("apple","car")##format可以更改要输出的字符串的顺序,{1}表示显示第二个字符串,{0}表示显示第一个字符串f = "this is a {1} or {0} " .format ("apple","car")#format的高级用法,指定特定参数赋值g = "this is a {fruit} or {gongji} " .format (fruit = "apple",gongji = "car")print aprint bprint cprint dprint '---------this is e---------'print eprint '---------this is f---------'print fprint '---------this is g---------'print groot@72132server:~/python/laowangpy# python geshihua.py this is a applethis is a 4this is a 4 or 10 this is a apple or car ---------this is e---------this is a apple or car ---------this is f---------this is a car or apple ---------this is g---------this is a apple or car root@72132server:~/python/laowangpy# #3、为什么要用format#强烈推荐使用高级方法#4、还有一个方法,字典来了root@72132server:~/python/laowangpy# cat geshihua.py #!/usr/bin/pyton# --*-- coding:utf-8 --*--#%d 表示格式化数字  %s 表示格式化字符串a = "this is a %s" % 'apple'b = "this is a %s" % 4#%s是根据顺序完成输出字符串的,是不可以更改顺序的c = "this is a %s or %s " % (4,10)d = "this is a %s or %s " % ("apple","car")#format最基础的用法e = "this is a {} or {} " .format ("apple","car")##format可以更改要输出的字符串的顺序,{1}表示显示第二个字符串,{0}表示显示第一个字符串f = "this is a {1} or {0} " .format ("apple","car")#format的高级用法g = "this is a {fruit} or {gongji} " .format (fruit = "apple",gongji = "car")#使用字典配合format格式化,输入数据h = "this is %(gongji)s or %(fruit)s " % {"gongji":"car","fruit":"apple"}print aprint bprint cprint dprint '---------this is e---------'print eprint '---------this is f---------'print fprint '---------this is g---------'print gprint '---------this is h---------'print hroot@72132server:~/python/laowangpy# python geshihua.py this is a applethis is a 4this is a 4 or 10 this is a apple or car ---------this is e---------this is a apple or car ---------this is f---------this is a car or apple ---------this is g---------this is a apple or car ---------this is h---------this is car or apple root@72132server:~/python/laowangpy# #四、再议打开文件#1、文件读取与写入常用方式,只能写入字符串,不可写入数值>>> g = open('/root/python/oldtext.txt','w')>>> g.write(1)#只能写入字符串,不可写入数值Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: expected a character buffer object>>> g.write("this is my test !!!\ntest is running!")>>> g.close()>>> >>> g.open('/root/python/oldtext.txt','r')Traceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: 'file' object has no attribute 'open'>>> g = open('/root/python/oldtext.txt','r')>>> g.read(1000)'this is my test !!!\ntest is running!'>>> g.read(1000)''>>> g.seek(0)>>> g.read(1000)'this is my test !!!\ntest is running!'>>> #2、使用标准库介绍 linecache库,对文件进行高级的读、写操作root@72132server:~/python/laowangpy# cat /root/python/oldtext.txt hahahhahahahhahnhahhhhharoot@72132server:~/python/laowangpy# root@72132server:~/python/laowangpy# >>> h = open('/root/python/oldtext.txt','w')>>> h.write('hahahha\nhahah\nhahn\nhah\nhhhha')>>> import linecache>>> help(linecache)>>> Help on module linecache:NAME    linecache - Cache lines from files.FILE    /usr/lib/python2.7/linecache.pyMODULE DOCS    http://docs.python.org/library/linecacheDESCRIPTION    This is intended to read lines from modules imported -- hence if a filename    is not found, it will look down the module search path for a file by    that name.FUNCTIONS    checkcache(filename=None)        Discard cache entries that are out of date.        (This is not checked upon each call!)    clearcache()        Clear the cache entirely.    getline(filename, lineno, module_globals=None)DATA    __all__ = ['getline', 'clearcache', 'checkcache'](END)#在测试环境运行失败#1)可以单行读出信息>>> h = open('/root/python/oldtext.txt','w')>>> h.write('hahahha\nhahah\nhahn\nhah\nhhhha\n')>>> import linecache>>> h.close()>>> print linecache.getline('/root/python/newtext.txt',1)>>> print linecache.getline('/root/python/oldtext.txt',1)this is my test !!!>>> print linecache.getline('/root/python/oldtext.txt',2)test is running!>>> print linecache.getline('/root/python/oldtext.txt',3)>>> 

这里写图片描述

2)、完全读取,放入一个list列表中>>> lines = linecache.getlines('/root/python/oldtext.txt')>>> print lines['this is my test !!!\n', 'test is running!\n']>>> 

可以使用help(linecache),查看linecache文件源文件中的getlines与getline方式是怎样编写的

原创粉丝点击