[笔记]--Python字符串处理

一、截取字符串中的内容

1、截取: MsiExec.exe /I{AC76BA86-7AD7-2052-7B44-AB0000000001} 中的: {AC76BA86-7AD7-2052-7B44-AB0000000001} 包括大括号

>>> import re
>>> text = 'MsiExec.exe /I{AC76BA86-7AD7-2052-7B44-AB0000000001}'
>>> re.findall(r'{[^}]*}', text)
['{AC76BA86-7AD7-2052-7B44-AB0000000001}']

[^}] 是指不是 } 的字符, {[^}]*} 是指由 { 开始、 } 结束的至少0个不是 } 的字符

或者

re.findall(r'{.*?}', text)

注意:{.*}{.*?}的区别,前者是贪婪模式,后者是非贪婪模式

2、截取: MsiExec.exe /I{AC76BA86-7AD7-2052-7B44-AB0000000001} 中的: AC76BA86-7AD7-2052-7B44-AB0000000001 不包括大括号

>>> import re
>>> text = 'MsiExec.exe /I{AC76BA86-7AD7-2052-7B44-AB0000000001} abc } { xyz }'
>>> re.findall(r'(?<={).*?(?=})', text)
['AC76BA86-7AD7-2052-7B44-AB0000000001', ' xyz ']
>>> re.findall(r'(?<={)[^}]*(?=})', text)
['AC76BA86-7AD7-2052-7B44-AB0000000001', ' xyz ']


(?<={) 匹配左边是 { 的位置
(?=}) 匹配右边是 } 的位置

二、匹配字符串,并且截取匹配的内容

1、匹配“softname_3.5.7896.all”,并且截取“7896” 

>>> import re
>>> text = "softname_3.5.7896.all"
>>> handle = re.compile(r'softname_3.5.([0-9]{4}).all')
>>> m = handle.match(text)
>>> m.group(0)
'softname_3.5.7896.all'
>>> m.group(1)
'7896'

其中:group(0)表示匹配到的整个字符串,group(1)表示正则表达式中第1个括号匹配的字符,group(2)表示正则表达式中第2个括号匹配的字符,一次类推;

三、随机产生字符串

方法1:

import string
import random
def RandomChar():
    random_char = ''.join(random.sample(string.ascii_letters + string.digits + string.punctuation, 50))
random_char = ''.join([random.choice(string.letters+string.digits) for e in range(100)])
return random_char

方法2:

import os
def randomString(n):
    return (''.join(map(lambda xx:(hex(ord(xx))[2:]),os.urandom(n))))[0:16]

print randomString(16)

方法2没搞懂!

参考文档:

原文地址:https://www.cnblogs.com/lizhishugen/p/3182016.html