字符串比较:实际换行符永远不会被识别为“\ n”

时间:2014-06-07 20:17:15

标签: python string serial-port

我正在尝试通过编写脚本来学习一些Python,以通过串行连接与我的交换机进行通信。

    while char is not "\n":
        char = port.read(1)
        sys.stdout.write(char)

我尝试比较输出并结束循环,如果我找到换行符但它永远不会起作用。

我甚至尝试对某些输出进行编码以确保确实存在新行,看起来像这样:

0000420   G   I   G   A   l   i   n   e   2   6   0   0   M       l   o
0000440   g   i   n   :      \r  \n   G   I   G   A   l   i   n   e   2
0000460   6   0   0   M       l   o   g   i   n   :      \r  \n   G   I
0000500   G   A   l   i   n   e   2   6   0   0   M       l   o   g   i
0000520   n   :      \r  \n   G   I   G   A   l   i   n   e   2   6   0 ...

可能是什么问题?

2 个答案:

答案 0 :(得分:4)

你想要

while char != "\n":

在比较中使用is检查比较中的两个对象是否完全相同,它不会检查它们是否只有相同的值。

>>> char = "\n"
>>> char == "\n"
True
>>> char is "\n"
False
>>> a = char
>>> a is char
True
>>> id(a)
139751408202160
>>> id(char)
139751408202160  # char and a have the same id, thus `a == char` is True
>>> id("\n")
139751346017264  # "\n" has a different id, so `char is "\n"` is False

作为一项规则,您只应在处理单身对象时使用Python中的is比较,例如NoneTrueFalse 。对于字符串,整数等,您应该使用==!=

答案 1 :(得分:0)

!=并不是python中不一样的东西。

喜欢==并且是不同的。

a = 'a'
# char is not equals a
char != 'a'
# char is not a
char is not a

# char is equals a
char == a
# char is a
char is a