结果显示,而不是Python中的实际换行符



从 2 个不同的字符串开始,我尝试遍历 string1 n 次,并将子字符串与 string2 进行比较,看看它是否与该字符串中的任何子字符串匹配。如果子字符串匹配,则会追加到列表中。我的问题是我如何让列表打印换行符,而不是在某些子字符串中保存到列表中的。

例 子字符串长度 3

字符串 1:

Yo.
dey do!!
yo'yo. yoyo.

字符串 2:

yo.
dey do!!
yo'yo. yoyo.

我的结果是:

o.n
.nd
nde
dey
ey 
y d
do
do!
o!!
!!n
!nn
nny
nyo
yo'
o'y
'yo
yo.
o. 
. y
yo
yoy
oyo
o.

正确的结果应该是:

!!
o.
'yo
!

yo.
.
d

y
dey
yoy
o. 
ey 
de
y d
yo
. y
yo'
oyo
yo
o'y
o!!
do
do!

这是代码:

def substrings(a, b, n):
"""Return substrings of length n in both a and b"""
all_sub = list()
i = 1
for h in range(len(a)):
i = 1
sub = a[h]
if h+n > len(a):
n = len(a) - h
while i < n:
sub += str(a[h+i])
i += 1
if i == n:
if sub in b:
all_sub.append(sub)
all_sub = list(dict.fromkeys(all_sub))
return all_sub
# Compare files
if args["lines"]:
matches = lines(file1, file2)
elif args["sentences"]:
matches = sentences(file1, file2)
elif args["substrings"]:
matches = substrings(file1, file2, args["substrings"])
# Output matches, sorted from longest to shortest, with line endings escaped
for match in sorted(matches, key=len, reverse=True):
print(match.replace("n", "\n").replace("r", "\r"))

def positive(string):
"""Convert string to a positive integer."""
value = int(string)
if value <= 0:
raise argparse.ArgumentTypeError("invalid length")
return value

if __name__ == "__main__":
main()

n替换为\n将打印n具有换行符的位置。

match.replace("n", "\n").replace("r", "\r")更改为仅match以停止转义换行符。