zoukankan      html  css  js  c++  java
  • day4-基础 字符串操作,文件操作,字符转编码


     1.字符串用法

     1 name = 'daniel'
     2 
     3 print(name.capitalize())         #首字母大写
     4 >>>daniel          
     5 print(name.count('a'))           #统计指定的字符
     6 >>>1
     7 print(name.center(50,'-'))      #一共打印50个字符,不够就用-代替,将name放在中间
     8 >>>----------------------daniel----------------------    
     9 print(name.endswith('el'))      #判断结尾是不是'el'
    10 >>>True
    11 print(name.expandtabs(tabsize=30)) #如果在一个字符前面输入	(tab)的话就会自动打印三十个空格
    12 >>>daniel
    13 print(name.find('a'))       #查找制定字符的位置    
    14 >>>1
    15 names = '{name} is {year} years old'    
    16 print(names.format(name='Daniel',year=18))     #为临时变量赋值
    17 >>>Daniel is 18 years old
    18 print(name.index('d'))    #获取指定字符的下标
    19 >>>0
    20 print(name.isdigit())       #判断变量是否是证书
    21 >>>Flase
    22 print(name.isalnum())    #判断变量是否为阿拉伯字符(包含数字和英文)
    23 >>>True
    24 print(name.isalpha())     #判断变量是否为纯英文字符
    25 >>>True
    26 print(name.isdecimal())  #判断变量为10进制数字
    27 >>>False
    28 print(name.isidentifier())  #判断是不是一个合法的变量名
    29 >>>True
    30 print(name.islower())       #判断变量是否为小写
    31 >>>True
    32 print(name.isnumeric())    #判断变量是否只有数字
    33 >>>False
    34 print(name.istitle())          #判断变量是否是首字母大写(每个单词)
    35 >>>False
    36 print(name.isprintable())   #判断是否能打印
    37 >>>True
    38 print(name.isupper())       #判断是否全部都是大写
    39 >>>False
    40 print('+'.join(['1','2','3']))   #将列表中的东西加入到'+',不能是str,如果是数字就要''放入
    41 >>>1+2+3       
    42 print(name.ljust(50,'*'))   #打印五十个字符,不够就用*代替放在右边
    43 >>>daniel********************************************
    44 print(name.lrjust(50,'*'))  #与上面相反
    45 print(name.lower())          #将大写变成小写
    46 >>>daniel
    47 print(name.upper())         #将小写变成大写
    48 >>>DANIEL
    49 print('
    Danile'.lstrip)         #删除左边的空格
    50 print('Daniel
    '.rstrip)       #删除右边的空格
    51 print('
    Daniel
    '.strip)      #删除所有的空格
    52 print('DanielDD'.replace('D','d',1)) #替换后面的1表示只替换第一个
    53 >>>danielDD
    54 print('Daniel DD'.rfind('D'))   #找到指定的值的最右边的下标
    55 >>>8
    56 print('Daniel 1 2 3 4'.split())  #使用指定的字符为分隔符,分割成列表,默认为空格
    57 >>>['Daniel', '1', '2', '3', '4']
    58 print('Daniel 1 2 3 4'.splitlines())  #同上,可识别不同系统
    59 print('Dianiel'.swapcase())           #大写变小写
    60 >>>dANIEL
    61 name = "Daniel","Man"
    62 print('is'.join(name))                #字符串拼接
    63 >>>Danieliszhaoyue

     2.集合操作

    集合是一个无序的,不重复的数据组合,它的主要作用如下:

    • 去重,把一个列表变成集合,就自动去重了
    • 关系测试,测试两组数据之前的交集、差集、并集等关系

    常用操作:

    a = set([1,2,3,4,5]) #创建数值集合
    b = set(['Hello'])    #创建字符集合
    c = set([1,3,5,888])
    print(a | b)            #a和b的并集
    print(a.union(b))   #同上
    >>>{1, 2, 3, 4, 5, 'Hello'}
     
    print(a & c)           #a和c的交集
    print(a.intersection(c))  #同上
    >>>{1, 3, 5}        
    
    print(a - c)            #a和c的差集
    print(a.difference(c))     #同上
    >>>{2, 4}
     
    print(a ^ c)           #对称差集,在a或b中,不会同时在两者中
    print(a.symmetric_difference(c))  #同上
    >>>{2, 4, 888}

    基本操作:

     1 c.add('xxx')         #添加一项
     2 a.update([111,222,333])    #添加多项
     3 print(a,c)
     4 >>>{1, 2, 3, 4, 5, 333, 111, 222} {1, 3, 5, 'xxx', 888}
     5 
     6 a.remove(5)         #删除一项
     7 print(a)
     8 >>>{1, 2, 3, 4, 333, 111, 222}
     9 
    10 print(len(a))             #a的长度,跟list的index一样
    11 >>>7
    12   
    13 print(3 in a)             #判断3是不是在a里面,也可以判断其它的集合
    14 >>>True        
    15 
    16 print(3 not in a)      #与上相反
    17 >>>False
    18 
    19 print(b.issubset(a))   #判断b中的所有元素a里面是否都有
    20 print(b <= a)                #意思同上
    21 >>>Flase
    22 
    23 print(b.issuperset(a))   #判断a里的所有元素b是否全有
    24 print(b >= a)              #意思同上
    25 >>>Flase

    3.文件操作

    对文件操作流程

    1. 打开文件,得到文件句柄并赋值给一个变量
    2. 通过句柄对文件进行操作
    3. 关闭文件

    基本操作:

      文件内容:

    1 你等着一辆火车,
    2 它会把你带到远方.
    3 你明白自己希望火车把你带到哪儿,
    4 不过你也心存犹豫,
    5 但这一切都没有关系.
    6 ——因为我们在一起.
    Inception space
    1 f = open('E:/python/file/test.txt')
    2 print('first line:',f.readline())
    3 >>>first line: 你等着一辆火车,
    4 print(f.read())
    5 >>>它会把你带到远方.
    6     你明白自己希望火车把你带到哪儿,
    7     不过你也心存犹豫,
    8     但这一切都没有关系.
    9     ——因为我们在一起.

    打开文件的模式有:

    • r,只读模式(默认)。
    • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
    • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

    "+" 表示可以同时读写某个文件

    • r+,可读写文件。【可读;可写;可追加】
    • w+,写读
    • a+,同a

    "U"表示在读取时,可以将 自动转换成 (与 r 或 r+ 模式同使用)

    • rU
    • r+U

    "b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)     

    • rb
    • wb
    • ab

    其它语法:

    1 f.tell()   #查看现在的光标位置
    2 
    3 f.seek(0)   #指定光标回到哪里,多用于文件重新读取,和tell一起使用
    4 
    5 f.flush()  #刷新
    6 
    7 f.truncate(10)  #截断,默认从0开始,后面是结束
    8 print(f.read())
    9 >>>你等着一辆

    补充:

     1 #with 语句
     2 #为了避免打开文件后忘记关闭,可以通过管理上下文,即:
     3 
     4 with open('file','r') as f:    #与f = open('file','r')一样
     5 
     6 
     7 如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
     8 
     9 在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
    10 
    11 with open('file1','r') as f1 , open('file2','r') as f2:

    4.字符转编码操作:

    超级超级详细版!!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>http://www.cnblogs.com/yuanchenqi/articles/5956943.html

    1).在python2默认编码是ASCII, python3里默认是unicode

    2).unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-16就是现在最常用的unicode版本, 不过在文件里存的还是utf-8,因为utf8省空间

    3).在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string

    文件操作小实例

    要求:

    现有配置文件httpd.conf,内容如下:

    <VirtualHost *:80>
    DocumentRoot /var/www/html/
    ServerName www.baidu.com
    ErrorLog "logs/baidu.com-error.log"
    CustomLog "logs/baidu.com-access.log" common
    </VirtualHost>

    backend www.baidu.com
    server 1.1.1.1 1.1.1.1 weight 100 maxconn 2000
    server 2.2.2.2 2.2.2.2 weight 100 maxconn 2000
    backend www.sina.com
    server 3.3.3.3 3.3.3.3 weight 100 maxconn 3000
    server 4.4.4.4 4.4.4.4 weight 100 maxconn 3000

    对这个文件可进行增删查改操作

    增加:是增加一条backend记录,是一整块,包括下面的server

    删除:可以删除一条server

    查询:查询到输入的backend"xxx.xxx.com"以下的server内容

    修改:改backend记录中的一条server

      1 # -*-conding:utf-8-*-
      2 #Author:Daniel
      3 
      4 import os
      5 
      6 def file_operation(filename,data_backend,return_list,type):
      7     '''
      8     统一文件操作接口
      9     :param filename: 传入原文件名字
     10     :param data_backend: 自己拼接一个完整的"backend"
     11     :param return_list: "backend"下"server"字段,以一个列表存放
     12     :param type: 文件类型,用于具体操作文件
     13     :return: 
     14     '''
     15     if type == 'query':
     16         tag = False
     17         data_list = []
     18         with open(filename, 'r') as f:
     19             for i in f:
     20                 if i.strip() == data_backend:
     21                     tag = True
     22                     continue
     23                 if tag and i.startswith("backend"):
     24                     tag = False
     25                     break
     26                 if tag and i:
     27                     data_list.append(i.strip())
     28         return data_list
     29     elif type == 'add':
     30         with open(filename, 'r') as read_file, 
     31                 open("haproxy_new.txt", 'w') as write_file:
     32             for i in read_file:
     33                 write_file.write(i)
     34             for i in return_list:
     35                 if i.startswith("backend"):
     36                     write_file.write(i + "
    ")
     37                 else:
     38                     write_file.write("%s%s
    " % (' ' * 4, i))
     39         os.remove(filename)
     40         os.rename("haproxy_new.txt", filename)
     41     elif type == 'change':
     42         with open(filename, 'r') as read_file, 
     43                 open("haproxy_new.txt", 'w') as write_file:
     44             tag = False
     45             tag_2 = False
     46             for i in read_file:
     47                 if i.strip() == data_backend:
     48                     tag = True
     49                     continue
     50                 if i.startswith("backend"):
     51                     tag = False
     52                 if not tag:
     53                     write_file.write(i)
     54                 else:
     55                     if not tag_2:
     56                         for i in return_list:
     57                             if i.startswith("backend"):
     58                                 write_file.write(i + "
    ")
     59                             else:
     60                                 write_file.write("%s%s
    " % (' ' * 4, i))
     61                         tag_2 = True
     62         os.remove(filename)
     63         os.rename("haproxy_new.txt", filename)
     64 
     65     else:
     66         print("啥也不是")
     67 
     68 def query(data):
     69     '''
     70     用户查询接口
     71     :param data:用户输入的数据,例子:www.baidu.com
     72     :return: 
     73     '''
     74     data_backend = "backend %s" % data
     75     return_list = file_operation('haproxy.txt',data_backend,None,type='query')
     76     for i in return_list:
     77         print(i)
     78     return return_list
     79 
     80 def add(data):
     81     '''
     82     用户添加接口
     83     :param data:用户输入的数据,必须是字典形式,例如{"backend":"www.faker.com","server":"6.6.6.6","weight":"20","maxconn":3000}
     84     这里,文件如果没有backend字段会将这个字典存进去,如果有则会存server字段
     85     :return: 
     86     '''
     87     backend = data["backend"] #取值
     88     return_list = query(backend) #取值,query函数返回的一个列表
     89     data_backend = "backend %s" % backend  #自己拼接的backend字段
     90     server_value = "server %s %s wieght %s maxconn %s" % (data["server"],
     91                                                           data["server"],
     92                                                           data["weight"],
     93                                                           data["maxconn"]) #自己拼接的server字段
     94     if not return_list:
     95         return_list.append(data_backend)
     96         return_list.append(server_value)
     97         file_operation("haproxy.txt",data_backend,return_list,type="add")
     98     else:
     99         return_list.insert(0,data_backend)
    100         if server_value not in return_list:
    101             return_list.append(server_value)
    102             file_operation("haproxy.txt", data_backend, return_list, type="change")
    103 
    104 def remove(data):
    105     '''
    106     用户删除接口
    107     :param data: 用户输入的数据,必须是字典形式,例如{"backend":"www.faker.com","server":"6.6.6.6","weight":"20","maxconn":3000}
    108     这里,文件如果没有backend字段或者server字段会出现提示信息,如果有则删除server字段
    109     :return: 
    110     '''
    111     backend = data["backend"]
    112     return_list = query(backend)
    113     data_backend = "backend %s" % backend
    114     server_value = "server %s %s weight %s maxconn %s" % (data["server"],
    115                                                           data["server"],
    116                                                           data["weight"],
    117                                                           data["maxconn"])
    118     if not return_list or server_value not in return_list:
    119         print("33[31;1m没找到33[0m")
    120 
    121     else:
    122         return_list.insert(0,data_backend)
    123         return_list.remove(server_value)
    124         file_operation("haproxy.txt", data_backend, return_list, type="change")
    125 
    126 def modify(data):
    127     '''
    128     用户输入的数据,必须是列表形式,例如[{"backend":"www.faker.com","server":"6.6.6.6","weight":"20","maxconn":3000},
    129     {"backend":"www.faker.com","server":"5.5.5.4","weight":"20","maxconn":3000}]
    130     这里,文件如果没有backend字段或者server字段会出现提示信息,如果有则修改server字段,列表第0个值为旧值,第二个值则为新值
    131     :param data:"data"传进来是个列表,0为要修改的旧值,1为修改的新值
    132     :return:
    133     '''
    134     backend = data[0]["backend"]
    135     return_list = query(backend)
    136     data_backend = "backend %s" % backend
    137     old_server_value = "server %s %s weight %s maxconn %s" % (data[0]["server"],
    138                                                               data[0]["server"],
    139                                                               data[0]["weight"],
    140                                                               data[0]["maxconn"])
    141     new_server_value = "server %s %s weight %s maxconn %s" % (data[1]["server"],
    142                                                               data[1]["server"],
    143                                                               data[1]["weight"],
    144                                                               data[1]["maxconn"])
    145     if not return_list or old_server_value not in return_list:
    146         print("33[31;1m没找着33[0m")
    147     else:
    148         return_list.insert(0,data_backend)
    149         index = return_list.index(old_server_value)
    150         return_list[index] = new_server_value
    151         file_operation("haproxy.txt", data_backend, return_list, type="change")
    152 
    153 if __name__ == '__main__':
    154     options = '''
    155         1.查询
    156         2.添加
    157         3.删除
    158         4.修改
    159         5.退出
    160     '''
    161     options_dict = {
    162         "1":query,
    163         '2':add,
    164         "3":remove,
    165         "4":modify,
    166         "5":exit,
    167     }
    168     while True:
    169         print(options)
    170         choice = input("选择>>:").strip()
    171         if len(choice) == 0 or choice not in options_dict:continue
    172         if choice == '5':break
    173 
    174         data = input("数据>>:").strip()
    175         if choice != '1':
    176             data = eval(data)
    177         options_dict[choice](data)
    View Code

     当然上面肯定会有一些小bug但是完成上面的四个功能,完全没问题

    随时都有可能更新的学霸版

      1 #!/usr/bin/env python
      2 # -*- coding:utf-8 -*-
      3 # Author: Daniel
      4 
      5 import os
      6 
      7 def query(data):
      8     if not data:
      9         data=input("请输入你要查询的域名>>:").strip()
     10     backend_data = "backend %s" % data
     11     tmp_list = []
     12     tag = False
     13     with open("httpd.txt","r") as r_file:
     14         for line in r_file:
     15             if line.strip() == backend_data:
     16                 tmp_list.insert(0,backend_data)
     17                 tag = True
     18                 continue
     19             if tag and line.startswith("backend"):
     20                 tag = False
     21             if tag:
     22                 tmp_list.append(line.strip())
     23     return tmp_list
     24 
     25 
     26 def add(data):
     27     backend = data["backend"]
     28     backend_data = "backend %s" % backend
     29     tmp_list = query(backend)
     30     splicing_server = "server %s %s weight %s maxconn %s" % (data["server"]["server"], 
     31                                                              data["server"]["server"], 
     32                                                              data["server"]["weight"],
     33                                                              data["server"]["maxconn"])
     34 
     35     if not tmp_list:
     36         tmp_list.append(backend_data)
     37         tmp_list.append(splicing_server)
     38         with open("httpd.txt", 'r') as r_file, 
     39                 open("http_new.txt", 'w')as w_file:
     40             for r_line in r_file:
     41                 w_file.write(r_line)
     42             for i in tmp_list:
     43                 if i.startswith("backend"):
     44                     w_file.write(i + "
    ")
     45                 else:
     46                     w_file.write("%s%s" % (" " *4,i))
     47     else:
     48         if splicing_server in tmp_list:
     49             print("此条目已存在")
     50             return
     51         else:
     52             tmp_list.append(splicing_server)
     53             ops(tmp_list,backend_data)
     54             print("添加完毕")
     55 
     56 def delete(data):
     57     backend = data["backend"]
     58     backend_data = "backend %s" % backend
     59     tmp_list = query(backend)
     60     splicing_server = "server %s %s weight %s maxconn %s" % (data["server"]["server"], 
     61                                                              data["server"]["server"], 
     62                                                              data["server"]["weight"],
     63                                                              data["server"]["maxconn"])
     64     if not tmp_list:
     65         print("不好意思,没有backend记录,请仔细检查一下")
     66         return
     67     else:
     68         if splicing_server not in tmp_list:
     69             print("不好意思,没有这条server记录")
     70             return
     71         else:
     72             tmp_list.remove(splicing_server)
     73             ops(tmp_list,backend_data)
     74             print("删除完毕")
     75 
     76 def update(data):
     77     if not data:
     78         data = input("请输入你要更新的域名记录:")
     79     # backend = data["backend"]
     80     # backend_data = "backend %s" % backend
     81     tmp_list = query(data)
     82     # splicing_server = "server %s %s weight %s maxconn %s" % (data["server"]["server"], 
     83     #                                                          data["server"]["server"], 
     84     #                                                          data["server"]["weight"], 
     85     #                                                          data["server"]["maxconn"])
     86     if not tmp_list:
     87         print("没有这个域名记录")
     88         return
     89     else:
     90         for i in tmp_list:
     91             print(i)
     92         server_record = input("请输入你要修改的Server记录>>:")
     93         if server_record not in tmp_list:
     94             print("没有这条Server记录")
     95         else:
     96             backend_data = "backend %s" % data
     97             new_record = input("请输入新修改的记录>>:")
     98             index = tmp_list.index(server_record)
     99             tmp_list[index] = new_record
    100             ops(tmp_list,backend_data)
    101 
    102 
    103 def ops(tmp_list,backend_data):
    104     tag = False
    105     write = False
    106     with open("httpd.txt", 'r') as r_file, 
    107             open("http_new.txt", 'w')as w_file:
    108         for i in r_file:
    109             if i.startswith(backend_data):
    110                 tag = True
    111                 continue
    112             if not tag:
    113                 w_file.write(i)
    114             if tag and not write:
    115                 for i in tmp_list:
    116                     if i.startswith("backend"):
    117                         w_file.write(i + "
    ")
    118                     else:
    119                         w_file.write("%s%s" % (" " * 4, i + "
    "))
    120                 write = True
    121             if tag and write and i.startswith("backend"):
    122                 w_file.write(i)
    123                 tag = False
    124     os.remove("httpd.txt")
    125     os.rename("http_new.txt", "httpd.txt")
    126 
    127 if __name__ == '__main__':
    128     msg='''
    129     1: 查询
    130     2: 添加
    131     3: 删除
    132     4: 更新
    133     5: 退出
    134     '''
    135     menu_dic = {
    136         "1":query,
    137         "2":add,
    138         "3":delete,
    139         "4":update,
    140     }
    141     while True:
    142         print(msg)
    143         choice = input(">>:").strip()
    144         if choice == "5":
    145             break
    146         if choice not in msg or len(choice) == 0:
    147             continue
    148         if choice != "1" and choice !="4":
    149             data = input("数据>>:").strip()
    150             try:
    151                 data = eval(data)
    152                 res = menu_dic[choice](data)
    153             except:
    154                 print("对不起,你输入的数据格式不对,(字典格式)")
    155                 continue
    156         else:
    157             data=""
    158             res = menu_dic[choice](data)
    159             if type(res) == list:
    160                 if not res:
    161                     print("没有!")
    162                 else:
    163                     for i in res:
    164                         print(i)
    View Code

  • 相关阅读:
    Codeforces Round #307 (Div. 2)E. GukiZ and GukiZiana
    bzoj2957: 楼房重建,分块
    分块入门。
    poj3690 Constellations
    Codeforces Round #451 (Div. 2)F. Restoring the Expression 字符串hash
    Codeforces Round #456 (Div. 2)D. Fishes
    Codeforces Round #450 (Div. 2)D. Unusual Sequences
    快速排序+分治法
    哈夫曼编码课程设计+最小优先对列建树。
    浅谈差分约束系统
  • 原文地址:https://www.cnblogs.com/wazy/p/7742820.html
Copyright © 2011-2022 走看看