python - 结果显示 \n 而不是 Python 中的实际换行
问题描述
从 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()
解决方案
替换\n
为\\n
将打印\n
您有换行符的位置。
更改match.replace("\n", "\\n").replace("\r", "\\r")
为只是match
停止转义换行符。
推荐阅读
- asp.net-mvc - 如何在 Kendo UI asp.net mvc Pivot 网格中隐藏总和列和行
- r - geom_boxplot,如何根据组专门为异常值着色并保持所有内容为黑色?
- c++ - 使用 tbb 运行时,Opencv 未定义对符号“_ZN3tbb18task_group_contextD1Ev”的引用
- scala - 不支持的文字类型类 scala.collection.immutable.HashSet$HashTrieSet
- android - Android约束布局,重量视图?
- php - 模拟我的班级私人服务财产
- java - 使用带有 Spring 缓存抽象的大数据(千兆字节)的磁盘缓存
- clickhouse - 在 ClickHouse 中过滤计数
- sql-server - '>' 附近的语法不正确
- python - 如何在python上发布表单请求