首页 > 解决方案 > 使用 print() 截断长字符串

问题描述

我尝试了以下代码

s='Python is an interpreted high-level programming language for general-purpose programming. Created by Guido van Rossum and first released in 1991, Python has a design philosophy that emphasizes code readability, notably using significant whitespace. It provides constructs that enable clear programming on both small and large scales'
s1='Python features a dynamic type system and automatic memory management. It supports multiple programming paradigms, including object-oriented, imperative, functional and procedural, and has a large and comprehensive standard library'
print(s,end='\r')
print(s1)

我得到的输出是

Python is an interpreted high-level programming language for general-purpose programming. Created by Guido van Rossum and first released in 1991, Python has a design philosophy that emphasizes code readability, notably using significant whitespace. It provides con
Python features a dynamic type system and automatic memory management. It supports multiple programming paradigms, including object-oriented, imperative, functional and procedural, and has a large and comprehensive standard library

第一个字符串s打印在两行上。\r然后从第二行开始打印第二个字符串。

我希望从第一个字符串的开头打印第二个字符串。是否可以使用print或应该使用任何其他功能?

标签: python

解决方案


这是您正在使用的终端仿真器的一项功能。是的,您可以使用 print 来执行此操作,您需要为您的终端类型输出适当的终端转义序列。

例如,如果您在类似终端仿真器的 xterm 中,转义序列在此处描述(该页面用于 bash,但 python 的语法非常相似)。您可能最感兴趣的转义序列是:

  • 保存光标位置:\033[s
  • 恢复光标位置:\033[u

如果您正在做一些更复杂的事情,您可能还会对curses库感兴趣。


推荐阅读