gpt4 book ai didi

Python2 : Difference between print and print() with '\r' escape character

转载 作者:行者123 更新时间:2023-12-01 00:43:02 24 4
gpt4 key购买 nike

我正在读取由硬件设备发送的数据帧,该数据帧使用字符 '\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'

这里发生了什么?

最佳答案

“\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

关于Python2 : Difference between print and print() with '\r' escape character,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57197279/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com