python正确的字符串常量_4.1 字符串常量(python)
《Python Linux系統管理與自動化運維》學習之路:
1、字符串介紹
定義字符串,單引號,雙引號
轉義字符,反斜杠‘\’
原始字符串,‘r’,抑制轉義
字符串較長較負責,可使用三引號定義,‘‘‘ ‘‘‘或""" """,三引號內的引號,換行符,制表符等特殊字符,都被認為是普通字符,多行字符串也不受代碼塊縮進規則限制,因為它本身就不是代碼,而是普通字符串。
兩個相連的字符串會自動組成一個新的字符串:
In [1]: s = ‘hello‘ ‘world‘
In [3]: s
Out[3]: ‘helloworld‘
字符串不可變,是字符的有序組合
下標訪問,分片操作
列表反序 s[::-1]
內置函數reversed(seq)
使用reversed()返回一個迭代器,需要使用循環來訪問
In [5]: s
Out[5]: ‘hello,world‘
In [8]: ‘‘.join(reversed(s))
Out[8]: ‘dlrow,olleh‘
In [15]: for i in reversed(s):
....: print(i)
....:
d
l
r
o
w
,
o
l
l
e
h
a.sort()是對列表a進行原地修改,而且只能修改列表
sorted(a)對字符串、列表、元組都能排序,該函數返回一個排序好的列表
2、字符串函數
通用操作
獲取字符串長度 len(x)
判斷元素是否存在于集合中: ‘x‘ in s
都可應用于元組,列表等有序集合中
與大小寫有關的方法:
upper 將字符串轉換為大寫
lower 將字符串轉換為小寫
isupper 判斷字符串是否都為大寫
islower 判斷字符串是否都為小寫
swapcase 將字符串中的大寫轉小寫,小寫轉大寫
capitalize 將首字母轉大寫
istitle 判斷字符串是不是一個標題
判斷類方法
s.isalpha 只包含字母,非空
s.isalnum 只包含字母和數字,非空
s.isspace 包含空格、制表符、換行符、非空
s.isdecimal 只包含數字,非空
字符串方法
判斷參數是否為字符串的前綴或后綴
startwith
endswith
實例:
[item for item in os.listdir(‘.‘) if item.startswith(‘index‘)]
In [28]: index = [item for item in os.listdir(‘.‘) if item.startswith(‘index‘)]
In [29]: size = [os.path.getsize(os.path.join(‘/root‘, item)) for item in index]
In [30]: print(size)
[20810, 20810, 2381, 20810, 20810, 20810, 20810, 2381, 20810]
查找類函數
find 查找字串在字符串中的位置,查找失敗,返回-1
index 與find類似,查找失敗,拋出ValueError異常
rfind 與find類似,區別在于從后查找
rindex 與index類似,區別在于從后查找
實例:
In [31]: s = ‘Return the lower index in S where substring sub is found‘
In [32]: s.find(‘in‘)
Out[32]: 17
可以指定查找范圍,如從下標18開始:
In [33]: s.find(‘in‘, 18)
Out[33]: 23
In [34]: s.find(‘not exist‘)
Out[34]: -1
判斷一個字符串是另一個字符串的字串,正確應使用in和not in
字符串操作方法
join 接受任何可迭代的對象,不止列表
實例:
In [38]: 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
字符串拼接:
>>> print(‘root‘, ‘/root‘, 100, sep=‘:‘)
root:/root:100
# 適合python3
拆分函數split(),默認是空白字符(空格。換行符,制表符)進行拆分
裁剪函數 strip(), rstrip(), lstrip()
實例:
In [4]: s = ‘root:x:0:0:root:/root:/bin/bash‘
In [5]: s.split(‘:‘)
Out[5]: [‘root‘, ‘x‘, ‘0‘, ‘0‘, ‘root‘, ‘/root‘, ‘/bin/bash‘]
In [7]: s = ‘a b c d‘
In [8]: s.split()
Out[8]: [‘a‘, ‘b‘, ‘c‘, ‘d‘]
In [9]: s = ‘ \thello, \tworld \n‘
In [12]: s.strip()
Out[12]: ‘hello, \tworld‘
In [13]: s.rstrip()
Out[13]: ‘ \thello, \tworld‘
In [14]: s.lstrip()
Out[14]: ‘hello, \tworld \n
可以給strip函數傳入參數,參數是需要裁剪的字符集和,字符串的順序不重要,重復字符沒有任何效果
In [15]: s = ‘##hello, world##‘
In [16]: s.strip(‘#‘)
Out[16]: ‘hello, world‘
In [17]: s.strip(‘###‘)
Out[17]: ‘hello, world‘
In [18]: s.strip(‘h#d‘)
Out[18]: ‘ello, worl‘
In [19]: s.strip(‘dh#‘)
Out[19]: ‘ello, worl‘
3、實例
使用python分析Apache的訪問日志
(1)統計PV,UV
#!/usr/bin/python
#-*- coding: UTF-8 -*-
from __future__ import print_function
ips = []
with open(‘access.log‘) as f:
for line in f:
ips.append(line.split()[0])
print(‘PV is {0}‘.format(len(ips)))
print(‘UV is {0}‘.format(len(set(ips))))
(2 )統計熱門資源
使用collections.Couter,使用方法與字典類似,對于普通的計數功能,比字典更加好用
In [26]: from collections import Counter
In [27]: c = Counter(‘abcba‘)
In [28]: c
Out[28]: Counter({‘a‘: 2, ‘b‘: 2, ‘c‘: 1})
In [29]: c[‘a‘] += 1
In [30]: c
Out[30]: Counter({‘a‘: 3, ‘b‘: 2, ‘c‘: 1})
In [31]: c[‘a‘] += 1
In [32]: c
Out[32]: Counter({‘a‘: 4, ‘b‘: 2, ‘c‘: 1})
In [33]: c
Out[33]: Counter({‘a‘: 4, ‘b‘: 2, ‘c‘: 1})
In [34]: c.most_common(2)
Out[34]: [(‘a‘, 4), (‘b‘, 2)]
In [35]: c[‘d‘] += 1
In [36]: c
Out[36]: Counter({‘a‘: 4, ‘b‘: 2, ‘c‘: 1, ‘d‘: 1})
In [37]: c.most_common(3)
Out[37]: [(‘a‘, 4), (‘b‘, 2), (‘c‘, 1)]
如果一個鍵不存在計數器中,直接對這個鍵操作運算也不會報錯,會添加進去
most_common 顯示Counter中取值最大的幾個元素
#!/usr/bin/python
#-*- coding: UTF-8 -*-
from __future__ import print_function
from collections import Counter
c = Counter()
with open(‘access.log‘) as f:
for line in f:
c[line.split()[6]] += 1
print(‘Popular resources : {0}‘.format(c.most_common(10)))
(3)分析錯誤請求數
#!/usr/bin/python
#-*- coding: UTF-8 -*-
from __future__ import print_function
d = {}
with open(‘access.log‘) as f:
for line in f:
key = line.split()[8]
d.setdefault(key, 0)
d[key] += 1
sum_requests = 0
error_requests = 0
for 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、字符串格式化 format
(1)占位符或下標形式訪問
In [6]: ‘{} is apple‘.format(‘apple‘)
Out[6]: ‘apple is apple‘
In [7]: ‘{0} is apple‘.format(‘apple‘)
Out[7]: ‘apple is apple‘
(2)關鍵字參數形式訪問
In [2]: dic1 = {‘a‘:1, ‘b‘:2, ‘c‘:3}
In [5]: ‘{a} is 1, {b} is 2, {c} is 3, {a} little {c}‘.format(**dic1)
Out[5]: ‘1 is 1, 2 is 2, 3 is 3, 1 little 3‘
(3)可直接訪問對象的屬性
(4)format功能
精度:
In [8]: ‘{:.2f}‘.format(3.1415926)
Out[8]: ‘3.14‘
顯示正數符合:
In [9]: ‘{:+.2f}‘.format(3.1415926)
Out[9]: ‘+3.14‘
寬度:
In [10]: ‘{:10.2f}‘.format(3.1415926)
Out[10]: ‘ 3.14‘
對其方式:
In [11]: ‘{:^10.2f}‘.format(3.1415926)
Out[11]: ‘ 3.14 ‘
填充符號:
In [12]: ‘{:_^10.2f}‘.format(3.1415926)
Out[12]: ‘___3.14___‘
千位分隔符:
In [13]: ‘{:,}‘.format(31415926)
Out[13]: ‘31,415,926‘
綜合顯示:
In [14]: ‘{:_^+20,.2f}‘.format(31415926)
Out[14]: ‘___+31,415,926.00___‘
原文地址:http://www.cnblogs.com/yshan13/p/7804299.html
總結
以上是生活随笔為你收集整理的python正确的字符串常量_4.1 字符串常量(python)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python易错点3
- 下一篇: js几种数组排序及sort的实现