Skip to main content
 首页 » 编程设计

python之在 Python 中打印格式化字符串的问题

2025年02月15日23zhengyun_ustc

我试图逐行解析文本文档,在这样做时我偶然发现了一些奇怪的行为,我认为这是由某种 ankh 符号 (☥) 的存在引起的。我无法在此处复制真实符号。 在我的代码中,我尝试确定每行的第一个字符中是否存在“+”符号。为了查看这是否有效,我添加了一个包含 bool 值和此字符串的打印语句。

我代码的相关部分:

with open(file_path) as input_file: 
    content = input_file.readlines() 
    for line in content: 
        plus = '+' in line[0:2] 
        print('Plus: {0}, line: {1}'.format(plus,line)) 

我可以尝试解析的文件:

+------------------------------ 
row 1 with some content 
+------+------+-------+------- 
☥+------+------+-------+------ 
|  col 1 | col 2 | col 3 ... 
+------+------+-------+------- 
|_ valu | val |    |   dsf |.. 
|_ valu | valu | ... 

我得到的输出:

Plus: True, line: +------------------------------

Plus: False, line: row 1 with some content

Plus: True, line: +------+------+-------+-------

♀+------+------+-------+------

Plus: False, line: | col 1 | col 2 | col 3 ...

Plus: True, line: +------+------+-------+-------

Plus: False, line: |_ valu | val | | dsf |..

Plus: False, line: |_ valu | valu | ...

所以我的问题是,为什么它只打印包含没有“Plus: True/False”符号的行。我应该如何解决这个问题? 谢谢。

请您参考如下方法:

您看到的是性别符号。它来自 original IBM PC character set并被编码为 0x0c,又名 FormFeed,又名 Ctrl-L。

如果您正在解析带有这些内容的文本数据,它们很可能被插入以指示打印机开始新页面。

来自 wikipedia :

Form feed is a page-breaking ASCII control character. It forces the printer to eject the current page and to continue printing at the top of another. Often, it will also cause a carriage return. The form feed character code is defined as 12 (0xC in hexadecimal), and may be represented as control+L or ^L.