在Python的终端中,我可以使用什么来执行一个换行操作?

2024-09-30 08:30:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以使用\b返回一个字符:

>>> print("123#456")
123#456
>>> print("123#\b456")
123456

但如果涉及到断线,它就不起作用:

>>> print("123#\n456")
123#
456
>>> print("123#\n\b456")
123#
456

有没有退路?

我问这个是因为我在前一行有进展:

53%

我用\b来更新这个值。但如果有人印了什么东西,它就碎了。我试图创建一个字符串缓冲区并打印足够的'\b'来补偿它,然后将缓冲区打印回来。但如果有断线就不行了。


Tags: 字符串字符缓冲区print断线n456b456
1条回答
网友
1楼 · 发布于 2024-09-30 08:30:46

一种可能(有点老套)的解决方案是使用“\033[1A”返回一行。用要跳回的行数替换1。还有其他几种转义序列可用于操作光标。查看完整的列表:http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x361.html

- Position the Cursor:
  \033[<L>;<C>H
     Or
  \033[<L>;<C>f
  puts the cursor at line L and column C.
- Move the cursor up N lines:
  \033[<N>A
- Move the cursor down N lines:
  \033[<N>B
- Move the cursor forward N columns:
  \033[<N>C
- Move the cursor backward N columns:
  \033[<N>D

- Clear the screen, move to (0,0):
  \033[2J
- Erase to end of line:
  \033[K

- Save cursor position:
  \033[s
- Restore cursor position:
  \033[u

请注意,这可能不适用于所有终端。

相关问题 更多 >

    热门问题