Python中的子字符串
我在Python中有一些字符串,格式如下:
2011-03-01 14:10:43 C:\Scan\raisoax.exe detected Trojan.Win32.VBKrypt.agqw
我想提取出这两个子字符串:C:\Scan\raisoax.exe 和 Trojan.Win32.VBKrypt.agqw
这两个字符串之间是一个制表符(Tab键的效果)
5 个回答
2
s = r"2011-03-01 14:10:43 C:\Scan\raisoax.exe detected Trojan.Win32.VBKrypt.agqw"
v = s.split()
print v[-1] # gives you Trojan.Win32.VBKrypt.agqw
print v[-3] # gives you C:\Scan\raisoax.exe
print " ".join(v[2:-2])
要处理文件名中的空格,可以试试
3
只需要使用Python字符串的子串方法。
s = r"2011-03-01 14:10:43 C:\Scan\raisoax.exe detected Trojan.Win32.VBKrypt.agqw"
s.split("\t")
这样就能得到你想要的结果。
['2011-03-01 14:10:43 C:\\\\Scan\\raisoax.exe detected', 'Trojan.Win32.VBKrypt.agqw']
3
这里有一个使用正则表达式的解决方案:
s = "2011-03-01 14:10:43 C:\Scan\raisoax.exe detected Trojan.Win32.VBKrypt.agqw"
reg = re.match(r"\S*\s\S*\s(.*)[^\ ] detected\s+(.*)",s)
file,name = reg.groups()
这个方法也能找到文件名中带空格的文件。不过,如果文件名里有“ detected ”这样的内容,它就会出错。(你可以加一个前向断言来解决这个问题。)