【问题标题】:Results show \n instead of actual new line in Python结果显示 \n 而不是 Python 中的实际换行
【发布时间】: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")

标签: python newline


【解决方案1】:

\n 替换为\\n 将打印\n,其中您有一个换行符。

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

【讨论】:

    猜你喜欢
    • 2019-08-10
    • 2017-11-23
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    相关资源
    最近更新 更多