结果显示\ n,而不是Pyhton中的实际新行

问题描述 投票:0回答:1

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

示例子串长度3

string1:

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()
python newline
1个回答
0
投票
match.replace("\n", "\\n").replace("\r", "\\r")更改为仅match以停止转义换行符。
© www.soinside.com 2019 - 2024. All rights reserved.