【发布时间】:2020-05-11 21:13:32
【问题描述】:
从 2 个不同的字符串开始,我尝试一次迭代 string1 n 次,每次都将子字符串与 string2 进行比较,看它是否匹配该字符串中的任何子字符串。如果子字符串匹配,则将其附加到列表中。我的问题是如何让列表打印换行符而不是 \n 在某些子字符串中保存到列表中。
示例 子串长度 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
!\n\n
\n\ny
\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()
【问题讨论】:
-
如果您确实想打印换行符,为什么要替换所有换行符的
match.replace("\n", "\\n").replace("\r", "\\r")?