day4-基礎 字符串操做,文件操做,字符轉編碼


 1.字符串用法html

 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)) #若是在一個字符前面輸入\t(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('\nDanile'.lstrip)         #刪除左邊的空格
50 print('Daniel\n'.rstrip)       #刪除右邊的空格
51 print('\nDaniel\n'.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.集合操做python

集合是一個無序的,不重複的數據組合,它的主要做用以下:linux

  • 去重,把一個列表變成集合,就自動去重了
  • 關係測試,測試兩組數據以前的交集、差集、並集等關係

經常使用操做:git

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}

 

基本操做:windows

 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.文件操做api

對文件操做流程app

  1. 打開文件,獲得文件句柄並賦值給一個變量
  2. 經過句柄對文件進行操做
  3. 關閉文件

基本操做:ide

  文件內容:函數

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 \n \r\n自動轉換成 \n (與 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 + "\n")
 37                 else:
 38                     write_file.write("%s%s\n" % (' ' * 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 + "\n")
 59                             else:
 60                                 write_file.write("%s%s\n" % (' ' * 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("\033[31;1m沒找到\033[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("\033[31;1m沒找着\033[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 + "\n")
 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 + "\n")
118                     else:
119                         w_file.write("%s%s" % (" " * 4, i + "\n"))
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
相關文章
相關標籤/搜索