首页 > 解决方案 > 在控制台的标题中放置一个变量(Python)

问题描述

我想在控制台窗口的标题中放置一个变量,但是一旦我运行此代码,控制台就会崩溃:

import ctypes

for i in range(1500000000):
   ctypes.windll.kernel32.SetConsoleTitleW("StackOverFlow - HELP -[" + i + "]")

标签: python

解决方案


如果与字符串连接,则该变量i只能是字符串。此语法告诉 python 尝试转换i为字符串并将其放置在%s.

ctypes.windll.kernel32.SetConsoleTitleW("StackOverFlow - HELP -[%s]" % i)

或者

ctypes.windll.kernel32.SetConsoleTitleW(f"StackOverFlow - HELP -[{i}]")

如果您使用的是 python3.6 及更高版本。或者

ctypes.windll.kernel32.SetConsoleTitleW("StackOverFlow - HELP -[{}]".format(i))

Kinda打破了python的禅宗:

应该有一种——最好只有一种——明显的方法来做到这一点。


推荐阅读