Python规则字切割

  • 本文关键字:规则 Python python
  • 更新时间 :
  • 英文 :


我有字符串:'./money.log_rotated.27.10.2011_17:15:01:[27-10-2011 17:07:02]'

我需要字符串:'27-10-2011 17:07:02'

我如何在python中做到这一点?

有很多方法可以做到这一点,其中一种方法是使用str.partition:

text='./money.log_rotated.27.10.2011_17:15:01:[27-10-2011 17:07:02]'
before,_,after = text.partition('[')
print(after[:-1])
# 27-10-2011 17:07:02

另一个是使用str.split:

before,after = text.split('[',1)
print(after[:-1])
# 27-10-2011 17:07:02

或str.find和str.rfind:

ind1 = text.find('[')+1
ind2 = text.rfind(']')
print(text[ind1:ind2])

所有这些方法都依赖于紧跟在第一个左括号[之后的所需子字符串。

前两个方法还依赖于text中以倒数第二个字符结尾的所需子字符串。最后一个方法(使用rfind)从右边搜索右括号的索引,因此它更通用一些,并且不依赖于那么多(可能偏离1)常量。

如果您的字符串始终具有相同的结构,这可能是最简单的解决方案:

s = r'./money.log_rotated.27.10.2011_17:15:01:[27-10-2011 17:07:02]'
s[s.find("[")+1:s.find("]")]
更新:

在看了其他一些答案后,这是一个轻微的改进:

s[s.find("[")+1:-1]

利用右方括号是字符串中的最后一个字符的事实

如果格式为"fixed",也可以使用

>>> s = './money.log_rotated.27.10.2011_17:15:01:[27-10-2011 17:07:02]'
>>> s[-20:-1:]
'27-10-2011 17:07:02'
>>> 

也可以使用正则表达式:

import re
s = './money.log_rotated.27.10.2011_17:15:01:[27-10-2011 17:07:02]'
print re.search(r'[(.*?)]', s).group(1)

尝试使用一个正则表达式:

import re
re.findall(".*[(.*)]", './money.log_rotated.27.10.2011_17:15:01:[27-10-2011 17:07:02]')
>>> ['27-10-2011 17:07:02']

可能是最简单的方法(如果你知道字符串总是以这种格式

)
>>> s = './money.log_rotated.27.10.2011_17:15:01:[27-10-2011 17:07:02]'
>>> s[s.index('[') + 1:-1]
'27-10-2011 17:07:02'

最新更新