python比较2个字符串的子部分,看看它们是否匹配

时间:2010-09-22 14:03:26

标签: python

我有2个字符串,例如

str1 = 'section1.1:  this is a heading for section 1'

str2 = 'section1.1:  this is a heading for section 1.1'

我想比较'section1.1:'之后的文本,并返回它是否相同。在示例中,它将返回false,因为第一个显示section 1,第二个显示section 1.1

弦的第一段可以是任何例如subsection2.5:但始终以:

结尾

使用Python执行此操作的最佳方法是什么?

5 个答案:

答案 0 :(得分:2)

使用字符串的split method仅拆分第一个:

>>> str1 = 'section1.1:  this is a heading for section 1'
>>> str2 = 'section1.1:  this is a heading for section 1.1'
>>> str1.split(':', 1)[1]
'  this is a heading for section 1'
>>> str2.split(':', 1)[1]
'  this is a heading for section 1.1'

答案 1 :(得分:2)

根据您对格式的了解程度,您可能会做这样的事情。

In [1]: str1 = 'section1.1:  this is a heading for section 1'
In [2]: str2 = 'section1.1:  this is a heading for section 1.1'
In [3]: if str1.split(":", 1)[1] == str2.split(":", 1)[1]: 
   ...:     print "true"


In [4]: str2 = 'section1.1:  this is a heading for section 1'

In [7]: if str1.split(":", 1)[1] == str2.split(":", 1)[1]:
   ...:     print "true"


   true

如果您担心尾随或引导空格不同,您可以随时删除回复。

(编辑:IPython会话中缺少行)

答案 2 :(得分:0)

您可以直接将其翻译成代码:

def compare( str1, str2):
   # I want to compare the text which comes after the first ':' (for example)
   def find_that_part( s ):
       idx = s.find(':') # where is the first ':'?
       return s[idx:] # the part after it

   # and return whether it is the same or not.
   return find_that_part(str1) == find_that_part(str2)

答案 3 :(得分:0)

其他答案中的split(":")解决方案运行正常。如果您已经以某种方式解析了第一部分(在冒号之前),并且您知道了长度,那么您可以像这样进行简单的字符串比较:

parsedUntilColon = "section1.1:" # for example

if str1[len(parsedUntilColon):] == str2[len(parsedUntilColon):]:
    print "strings are equal"

答案 4 :(得分:0)

单个衬里应该很酷!!

>>> str1 = 'section1.1:  this is a heading for section 1'
>>> str2 = 'section1.1:  this is a heading for section 1.1'
>>> cmp = lambda str1, str2: [x_.findall(str1) == x_.findall(str2) for x_ in [re.compile(':[\w*\s*\.*]*')]][0] and True
>>> cmp(str1, str2)
False