Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中\r(回车)是如何工作的_Python_Python 2.7 - Fatal编程技术网

在Python中\r(回车)是如何工作的

在Python中\r(回车)是如何工作的,python,python-2.7,Python,Python 2.7,操作系统:Windows 7 我的理解是\r将文本移动到页面的左侧 然而,当我执行此命令时: carriage_return = "I will use a carriage\rreturn" print carriage_return 我得到:返回使用马车 我所期待的是:返回好吧,看来您确实移动到了行的左侧。它只是留下了线的其余部分未动。请注意,return是6个字符,I will也是6个字符。\r将光标移到行的开头。 当您将回车移到开头并覆盖任何内容时,其效果与物理打字机中的效果相同。转

操作系统:Windows 7

我的理解是\r将文本移动到页面的左侧

然而,当我执行此命令时:

carriage_return = "I will use a carriage\rreturn"

print carriage_return
我得到:返回使用马车


我所期待的是:返回

好吧,看来您确实移动到了行的左侧。它只是留下了线的其余部分未动。请注意,
return
是6个字符,
I will
也是6个字符。

\r将光标移到行的开头。
当您将回车移到开头并覆盖任何内容时,其效果与物理打字机中的效果相同。

转义序列后的所有字符移到左边,并完全覆盖语句开头的字符数


在您的示例中,return在后面\r,它是5个字符,它替换了I will,这也是5个字符(不要忘记包含空格:p),因此它基本上替换了I will并打印return,使用一个回车

来添加它。如果要返回到开头并删除行的内容,可以这样做:

text = "Here's a piece of text I want to overwrite" 
repl = "BALEETED!" # What we want to write
print(text, end="\r") # Write the text and return
print(f'\r{repl: <{len(text)}}')
对于奖励积分,您不需要使用空格,您可以使用任何东西:

print('\r{0:░<{1}}'.format(repl, len(text)))

# Which becomes when extrapolated:
print('DELETED░░░░░░░░░░░░░░░░░░░░░░░░░░░░░')

print('\r{0:░它只是向左移动,不会删除行。您是如何执行此程序的?IDLE、CMD、Pycharm。@user571099perfect!您关于字符数的注释使它变得清晰了您是否使用过物理打字机?这样做会产生完全不同的效果…:)你的意思是它向下滚动一行?这不是一个完全严肃的评论。我只是说,如果你在打字机上键入现有文本,该文本不会被新文本替换。(否则我就很难在我的打字机上写出
Ø
)。
print('\r{0:░<{1}}'.format(repl, len(text)))

# Which becomes when extrapolated:
print('DELETED░░░░░░░░░░░░░░░░░░░░░░░░░░░░░')
from time import sleep
def overprint(text,repl, t=1, char=" "):
    print(text, end="\r")
    sleep(t) 
    print('\r{0:{1}<{2}}'.format(repl, char, len(text)))

overprint("The bomb will explode in one sec...", "BOOM!")