【问题标题】:Python2: Difference between print and print() with '\r' escape characterPython2:带有'\ r'转义字符的print和print()之间的区别
【发布时间】:2019-07-25 08:15:02
【问题描述】:

我正在读取由硬件设备发送的数据帧,该数据帧用字符'\r' 分隔帧的每个字段。在 python 2 中打印框架时,我发现了 printprint() 之间的差异以及消失字符的一些问题。

print()print 之间的一些区别可以在以下位置找到: What is the difference between print and print() in python 2.7 但这并不能解释我遇到的问题。

例如在执行时

>>>frame = 'word_1#\rword_2\r'
>>>print(frame)
word_2#
>>>print frame
word_2#

它们都是一样的,但我不明白为什么'#'被移到'word_2'的末尾以及为什么'word_1'消失了。

另外,printprint() 显示不同的结果:

>>>frame = 'word_1#\rword_2\r'
>>>print('data:', frame)
('data', 'word_1#\rword_2\r')  
>>>print 'data:', frame
word_2word_1#

这里print() 似乎按预期工作,但print 删除了'data' 单词并更改了单词的顺序。

最后,这个案子也让人迷惑:

>>> frame = 'word_1\r#word2\r#'
>>> print(frame)
#word2
>>> print frame
#word2
>>> print('data', frame)
('data', 'word_1\r#word2\r#')
>>> print 'data', frame
#word2ord_1

其中print()printprint('data', frame) 的工作方式似乎与之前的情况相同,但print 'data', frame 在更改顺序后从word_1 中删除了初始'w'

这里发生了什么?

【问题讨论】:

    标签: python python-2.7 printing


    【解决方案1】:

    '\r' 字符称为回车符。它的目标是将光标放在行首。

    我将重新编写代码以更好地解释它的作用:(| 是你的光标)

    
    >>> frame = 'word_1\r#word2\r#'
    >>> print(frame)
    word_1|                            # write word_1
    |word_1                            # put cursor on the beginning of the line
    #word2|                            # write #word2 but on top of word_1 since your cursor was at the beginning of the line
    |#word2                            # put cursor on the beginning of the line
    #|word2                            # rewrite the # on top of the previous one
    
    >>> print frame                    # Same things happens here
    #word2
    
    >>> print('data', frame)
    ('data', 'word_1\r#word2\r#')      # As pointer by U10-Forward this is printing an actual tuple
    
    >>> print 'data', frame
    data|                              # you write data
    dataword_1|                        # you write word_1
    |dataword_1                        # you put the cursor on the beginning of the line
    #word2ord_1|                       # you write #word2 on top of the previous print
    |#word2ord_1                       # cursor on the beginning of the line
    #|word2ord_1                       # you write again the #
    

    顺便说一句:除非您需要使用 Python2,否则请使用 Python3

    【讨论】:

    • 感谢您的详细解释
    【解决方案2】:

    它们都是一样的,但我不明白为什么'#'被移到'word_2'的末尾以及'word_1'为什么消失了。

    \r 是回车符,这意味着它将打印指针移动到行首,然后开始覆盖\r 之后的输出。

    因此,在您的情况下,word_2 中的字符数与 word_1 的字符数相同,因此在第一个 \r 之后,它会覆盖 word_1 以将输出生成为 word_2#

    【讨论】:

    • 非常感谢!!这也解释了第三种情况
    【解决方案3】:

    因为在 Python 2 中:

    print(...)
    

    正在处理一个普通的print ...,但只是简单地打印一个元组,而另一个不是。

    【讨论】:

    • 这并不能解释为什么字符会消失或移动位置
    猜你喜欢
    • 1970-01-01
    • 2011-04-02
    • 1970-01-01
    • 2013-10-27
    • 2012-07-04
    • 1970-01-01
    • 2016-03-03
    • 2011-03-16
    相关资源
    最近更新 更多