Python:比较两个字符串从一端保留差异
Python: compare two strings retain difference from one end
初学者,虽然有些相似,但还没有找到这个问题的答案。
如果我有两个字符串:
s1 = 'abcdefghijk'
s2 = 'abcdefghi'
如何获得 'jk'
作为输出? 'abcdefghi'
必须先匹配,然后我在最后得到差值
在此之后的下一个(如果我能回答第一个问题,我可能会弄清楚)是如果 s2 = 'cdefghi'
并且我仍然希望输出只是 'jk'
而不是 'ab'
和 'jk'
.
可以用find()
在s1
中找到s2
的第一个索引,即:
def after(s1, s2):
index = s1.find(s2)
# return None if s2 is not part of s1
# or if there are no characters behind s2 in s1
if index != -1 and index + len(s2) < len(s1):
return s1[index + len(s2):]
else:
return None
s1 = "abcdefghijk"
s2 = "cdefghij"
print(after(s1, s2))
您可以使用字符串方法 index
找到子字符串的开头,然后添加子字符串的长度以获得您想要开始计算额外差异的位置。
base = 'abcdefghijk'
sub = 'abcdefghi'
def extra(base, sub):
start = base.index(sub)
end = start + len(sub)
return base[end:]
extra(base, sub)
如果sub
不是子字符串,这里会抛出一个ValueError
,此时你可以选择做你想做的。
编辑:根据您对问题的评论,return 什么都没有-我猜您的意思可能是一个空字符串-做:
def diff(base, sub):
try:
start = base.index(sub)
end = start + len(sub)
return base[end:]
except ValueError:
return ''
在这里使用 find
还是 index
可能取决于您实际想要使用它的目的。
对于第一种情况,case s1 = 'abcdefghijk' s2 = 'abcdefghi' ,下面的方法也可以。
>>> set(s1) - set(s2)
{'j', 'k'}
>>> ''.join( set(s1) - set(s2))
'jk'
所以基本上可以将设置逻辑应用于字符串以提取所提到字符串的重叠和非重叠部分。
更多信息... https://docs.python.org/2/library/sets.html
但对于第二种情况,@user3760780 的建议似乎是最合适的。
初学者,虽然有些相似,但还没有找到这个问题的答案。
如果我有两个字符串:
s1 = 'abcdefghijk'
s2 = 'abcdefghi'
如何获得 'jk'
作为输出? 'abcdefghi'
必须先匹配,然后我在最后得到差值
在此之后的下一个(如果我能回答第一个问题,我可能会弄清楚)是如果 s2 = 'cdefghi'
并且我仍然希望输出只是 'jk'
而不是 'ab'
和 'jk'
.
可以用find()
在s1
中找到s2
的第一个索引,即:
def after(s1, s2):
index = s1.find(s2)
# return None if s2 is not part of s1
# or if there are no characters behind s2 in s1
if index != -1 and index + len(s2) < len(s1):
return s1[index + len(s2):]
else:
return None
s1 = "abcdefghijk"
s2 = "cdefghij"
print(after(s1, s2))
您可以使用字符串方法 index
找到子字符串的开头,然后添加子字符串的长度以获得您想要开始计算额外差异的位置。
base = 'abcdefghijk'
sub = 'abcdefghi'
def extra(base, sub):
start = base.index(sub)
end = start + len(sub)
return base[end:]
extra(base, sub)
如果sub
不是子字符串,这里会抛出一个ValueError
,此时你可以选择做你想做的。
编辑:根据您对问题的评论,return 什么都没有-我猜您的意思可能是一个空字符串-做:
def diff(base, sub):
try:
start = base.index(sub)
end = start + len(sub)
return base[end:]
except ValueError:
return ''
在这里使用 find
还是 index
可能取决于您实际想要使用它的目的。
对于第一种情况,case s1 = 'abcdefghijk' s2 = 'abcdefghi' ,下面的方法也可以。
>>> set(s1) - set(s2)
{'j', 'k'}
>>> ''.join( set(s1) - set(s2))
'jk'
所以基本上可以将设置逻辑应用于字符串以提取所提到字符串的重叠和非重叠部分。
更多信息... https://docs.python.org/2/library/sets.html
但对于第二种情况,@user3760780 的建议似乎是最合适的。