The path of learning for Python Linux system Management and Automation operations:
1, String Introduction
defining strings, single quotes, double quotes
Escape character, backslash ' \ '
Original string, ' R ', suppressed escape
Strings longer and more responsible, you can use the three-quote definition, "" "or" "" "", three quotation marks, line breaks, tab characters, etc., are considered ordinary characters, multi-line string is not subject to code block indentation rules, because it is not code, but a normal string.
Two concatenated strings are automatically composed of a new string:
In [1]: s = ' Hello ' "World ' in [3]: sout[3]: ' HelloWorld '
String immutable, which is an ordered combination of characters
Subscript Access, shard operation
List reverse order S[::-1]
Built-in function reversed (seq)
Use reversed () to return an iterator that uses loops to access
In [5]: sout[5]: ' Hello,world ' in [8]: ". Join (Reversed (s)) out[8]: ' Dlrow,olleh ' in [+]: For I in reversed (s): ....:
print (i) ... .: Dlrow,olleh
A.sort () is an in-place modification of List A and can only modify the list
Sorted (a) can sort strings, lists, and tuples, which returns a sorted list
2. String functions
General operations
Gets the string length len (x)
Determines whether an element exists in the collection: ' X ' in S
can be applied to tuples, lists, and other ordered collections.
Case-sensitive methods:
Upper converting a string to uppercase
Lower converting a string to lowercase
Isupper to determine whether a string is uppercase
Islower to determine if a string is lowercase
Swapcase uppercase to lowercase in a string, lowercase to uppercase
Capitalize capitalize the initial letter
Istitle judge if a string is not a caption
Judging class methods
S.isalpha contains only letters, not empty
S.isalnum contains only letters and numbers, not empty
S.isspace contains spaces, tabs, line breaks, non-empty
S.isdecimal contains only numbers, not empty
String method
Determines whether a parameter is a prefix or suffix of a string
Startwith
EndsWith
Instance:
[Item for item in Os.listdir ('. ') if Item.startswith (' index ')]in ["]: index = [item for item in Os.listdir ('. ') I F item.startswith (' index ')]in [+]: size = [Os.path.getsize (Os.path.join ('/root ', item)) for item in Index]in [+]: print ( Size) [20810, 20810, 2381, 20810, 20810, 20810, 20810, 2381, 20810]
Find class functions
Find finds a string in the position of the strings, the lookup fails, returns-1
Index similar to find, find failed, throw ValueError exception
RFind is similar to find, except that it looks from behind
Rindex is similar to index, except that it looks from behind
Instance:
in [+]: s = ' Return The lower index in s where substring sub was found ' in [+]: s.find (' in ') out[32]: 17 You can specify a lookup range, such as starting with subscript 18: I n [[]: S.find (' in ', out[33]: 23In []: S.find (' not exist ') out[34]: 1
A string that is judged to be another string, should be used correctly in and not
String manipulation methods
Join accepts any object that can be iterated, more than a list
Instance:
in [+]: with open ('/etc/passwd ') as FD: ....: print (' # # # '. Join (FD)) ... .: root:x:0:0:root:/root:/ bin/bash## #bin: x:1:1:bin:/bin:/sbin/nologin## #daemon: x:2:2:daemon:/sbin:/sbin/nologin## #adm: X:3:4:adm:/var/adm :/sbin/nologin
string concatenation:
>>> print (' Root ', '/root ', sep= ': ') root:/root:100# suitable for Python3
Split function split (), which by default is a white space character (a space). line breaks, tabs) to split
Clipping function strip (), Rstrip (), Lstrip ()
Instance:
You can pass parameters to the strip function, which is the character set that needs to be cropped, and the order of the strings is unimportant, and the repeating characters have no effect
in [+]: s = ' # #hello, world## ' in [+]: S.strip (' # ') out[16]: ' Hello, World ' [+]: S.strip (' # # # ') out[17]: ' Hello, World ' I n [+]: S.strip (' h#d ') out[18]: ' Ello, Worl ' in []: S.strip (' dh# ') out[19]: ' Ello, Worl '
3. Example
Using Python to parse Apache access logs
(1) Statistical PV,UV
#!/usr/bin/python#-*-coding:utf-8-*-from __future__ Import print_functionips = []with open (' Access.log ') as F: for Line in F: Ips.append (Line.split () [0]) print (' PV are {0} '. Format (len (IPS))) print (' UV is {0} '. Format (len (set (IPS))) )
(2) Statistics of popular resources
Use collections. Couter, using the same method as the dictionary, for the normal counting function, more useful than the dictionary
in [+]: From collections import Counterin [+]: c = Counter (' ABCBA ') in []: cout[28]: Counter ({' A ': 2, ' B ': 2, ' C ': 1}) I n [+]: c[' a '] + = 1In [+]: cout[30]: Counter ({' A ': 3, ' B ': 2, ' C ': 1}) in [to]: c[' a '] + = 1In []: cout[32]: Counter ({' A ' : 4, ' B ': 2, ' C ': 1} ' in [[]: cout[33]: Counter ({' A ': 4, ' B ': 2, ' C ': 1}) in [the]: C.most_common (2) out[34]: [(' A ', 4], (' B ') , 2)]in [+]: c[' d '] + = 1In [+]: cout[36]: Counter ({' A ': 4, ' B ': 2, ' C ': 1, ' d ': 1}) in [PNS]: C.most_common (3) out[37]: [(' A ', 4), (' B ', 2), (' C ', 1)]
If a key does not exist in the counter, directly to this key operation operations will not be error, will be added in
Most_common displays the largest number of elements in the counter
#!/usr/bin/python#-*-coding:utf-8-*-from __future__ Import print_functionfrom Collections Import Counterc = Counter () w ITH open (' Access.log ') as F: For line in F: c[line.split () [6]] + = 1 print (' Popular resources: {0} '. Format (c.most_ Common (10)))
(3) Number of error requests analyzed
#!/usr/bin/python#-*-coding:utf-8-*-from __future__ Import print_functiond = {}with open (' Access.log ') as F: for Li NE in f: key = Line.split () [8] D.setdefault (key, 0) D[key] + = 1sum_requests = 0error_requests = 0for Key, Val In D.iteritems (): if int (key) >=400: error_requests = val sum_requests + val print (error_requests, sum _requests) print (' Error rate: {0:.2f}% '. Format (error_requests * 100.0/sum_requests))
4. String Formatting format
(1) Placeholder or subscript form access
In [6]: ' {} is Apple ', format (' Apple ') out[6]: ' Apple is Apple ' in [7]: ' {0} is Apple '. Format (' Apple ') out[7]: ' Apple is apple ‘
(2) keyword Parameter form access
In [2]: Dic1 = {' A ': 1, ' B ': 2, ' C ': 3}in [5]: ' {A} was 1, {B} is 2, {C} was 3, {a} little {c} '. Format (**DIC1) out[5]: ' 1 is 1, 2 is 2, 3 is 3, 1 little 3 '
(3) Properties for direct access to objects
(4) Format function
Accuracy: in [8]: ' {:. 2f} '. Format (3.1415926) out[8]: ' 3.14 ' shows a positive number in accordance with: in [9]: ' {: +.2f} '. Format (3.1415926) out[9]: ' +3.14 ' width: in [10 ]: ' {: 10.2f} '. Format (3.1415926) out[10]: ' 3.14 ' to its way: in [all]: ' {: ^10.2f} '. Format (3.1415926) out[11]: ' 3.14 ' Fill symbol: in []: ' {: _^10.2f} '. Format (3.1415926) out[12]: ' ___3.14___ ' thousands separator: in []: ' {:,} '. Format (31415926) out[13 ]: ' 31,415,926 ' integrated display: in [+]: ' {: _^+20,.2f} '. Format (31415926) out[14]: ' ___+31,415,926.00___ '
4.1 String Constants (Python)