一、字符串常量
intro = 'He\'s a teacher.'
statement = 'John said to me: \'Can you do me a favour tonight\''
抑制所有的转义:
path = r'c:\next'
在三重引号之间,所有的特殊字符,都会被认为是普通的字段
两个相连的字符串会自动组成一个新的字符串
s = 'hello' 'world'
2、字符串是不可变的有序集合
print(','.join(fruits))
元组、列表和字符串都是元素的有序集合,都可以使用下标和切片进行访问
s = 'hello,world'
print(s[:5])
print(s[0:5])
print(s[6:])
print(s[::-1])
置逆一个字符串
print(''.join(reversed(s)))
3、字符串函数
使用内置函数和表达式的方式提供支持的好处是,相同的方式可以应用于列表、元组等有序的集合中。
print(len(s))
print('hello' in s)
print('hello' not in s)
b、与大小写相关的方法
upper:将字符串转换为大写
lower:将字符串转换为小写
isupper:判断字符串是否都为大写
islower:判断字符串是否都为小写
swapcase:将字符串中的大写转换为小写、小写转换为大写
capitalize:将首字母转换为大写
istitle:判断字符串是不是一个标题
(这里的方法并没有改变原来的字符串,而是产生了一个新的字符串。如果需要修改字符串,则可以将修改过后的字符串赋值给原来的变量)
print('TEST'.isupper())
c、判断类方法
s.isalpha:只包含字母,并且非空,则返回True
s.isalnum:包含字母和数字,并且非空,则返回True
s.isspace:包含空格、制表符、换行符、并且非空,则返回True
s.isdecimal:只包含数字字符,并且非空
print('3.6'.isdecimal()) # False
d、字符串方法startswith和endswith
s = 'zhuang jia rui'
print(s.startswith('zhu'))
print(s.endswith('rui'))
找出所有文本文件或Python文件
import os
print([ item for item in os.listdir('.') if item.endswith('.py') ])
print([ item for item in os.listdir('.') if item.endswith('.txt') ])
所有MongoDB日志文件占用的磁盘大小
import os
mongod_logs = [ item for item in os.listdir('/var/mongo/log') if item.startswith('mongod.log') ]
sum_size = sum(os.path.getsize(os.path.join('/var/mongo/log', item)) for item in mongod_logs)
e、查找类函数
find:查找子串出现在字符串中的位置,如果查找失败,返回-1
index:与find函数类似,如果查找失败,抛出ValueError异常
rfind:与find函数类似,区别在于rfind是从后向前查找
rindex:与index函数类似,区别在于rindex是从后向前查找
判断一个字符串是否是另一个字符串的子串,正确的做法是使用in和not in。
f、字符串操作方法
join函数用以连接字符串列表,组成一个新的、更大的字符串
print(''.join(['a', 'b', 'c']))
join接收任何可迭代的对象
with open('/etc/passwd') as f:
print('###'.join(f))
join函数最容易被滥用的地方是打印字符串列表,print函数本身可以通过sep参数指定分隔符:
print('root', '/root', '/bin/bash', sep=':')
将一个字符串拆分成字符串列表:
print('root:x:0:0'.split(':'))
strip对字符串两边进行裁剪,lstrip对字符串左边进行裁剪,rstrip对字符串右边进行裁剪
strip最常用场景是除去字符串两边的空白字符
s = ' \tHello, \tWorld \n'
print(s.strip())
print(s.lstrip())
print(s.rstrip())
↓
s = '##Hello, world##'
print(s.strip('#'))
print(s.strip('###'))
print(s.strip('H#d'))
print(s.strip('d#H'))
replace函数,将字符串中的子串替换成另一个新的子串:
print('hello,world'.replace('ll', 'oo'))
4、
#!/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)))) # 用集合去重
对应普通的计数功能,Counter比字典好用
案例:统计网站中最热门的十项资源
#!/usr/bin/python
#-*- coding: utf-8 -*-
from __futrue__ 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 : {}'.format(c.most_common(10)))
如果HTTP CODE为2xx或3xx,则视为访问正确,如果HTTP CODE为4xx或5xx,则视为访问出错。
案例:统计网站的出错比例
#!/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_request+=val
print('error rate: {0:.2f}%',format(error_requests * 100.0 / sum_requests))
5、字符串格式化
二、正则表达式
import re
data = 'What is the difference between python 2.7.13 and Python 3.6.0 ?'
print(re.findall('python [0-9]\.[0-9]\.[0-9]', data, flags=re.IGNORECASE)) # 忽略大小写
使用正则表达式的第二种方式:创建一个特定模式编译的正则表达式对象,然后使用这个对象中的方法。
编译与非编译的差别,主要是性能方面的差异。
import re
data = 'What is the difference between python 2.7.13 and Python 3.6.0 ?'
re_obj = re.compile('python [0-9]\.[0-9]\.[0-9]', flags=re.IGNORECASE)
print(re_obj.findall(data))
2、常用的re方法
findall函数,该函数在字符串中查找模式匹配,将所有的匹配字符串以列表的形式返回。
import re
data = 'What is the difference between python 2.7.13 and Python 3.6.0 ?'
print(re.findall('python [0-9]\.[0-9]\.[0-9]', data, flags=re.IGNORECASE)) # 忽略大小写
match函数用以匹配字符串的开始部分,如果模式匹配成功,返回一个SRE_Match类型的对象,如果模式匹配失败,返回一个None。
# 判断一个文本字符串是否以一个数字开头
re.match('\d+', '123 is one hundred and twenty-three')
r.start()
r.end()
r.re
r.string
r.group()
finditer返回一个迭代器,遍历迭代器可以得到一个SRE_Match对象
data = 'What is the difference between python 2.7.13 and Python 3.6.0 ?'
r = re.finditer('[0-9]\.[0-9]\.[0-9]', data)
for it in r:
print(it.group(0))
b、“修改类”函数
sub函数支持使用正则表达式替换。
re模块的split函数能够指定多个分隔符。
c、非贪婪匹配
贪婪匹配总是匹配到最长的那个字符串,相应的,非贪婪匹配是指匹配到最小的那个字符串。
默认情况下,正则表达式使用贪婪匹配,如果要使用非贪婪匹配,只需要在匹配字符串时加上一个“?”。
————————————————
BY:HW-ZJR






































苏公安网备 32011402010933号