1

我目前正在用 Python 制作游戏。

我希望代码阅读:

[00:00:00]   Name|Hello!

这是我的代码:

print(Fore.YELLOW + Style.BRIGHT + '['),
print strftime("%H:%M:%S"),
print ']',
print(Style.BRIGHT + Fore.RED + ' Name'),
print(Fore.BLACK + '|'),
print(Fore.WHITE + Style.DIM + 'Hello!')
time.sleep(5)

相反 - 由于某种原因 - 它变成了这样:

[ 00:00:00 ]    Name | Hello!

我不知道这段代码有什么问题,或者如何修复它。

我真的很感激我能得到的所有帮助!谢谢你。

4

2 回答 2

5

使用单个print语句和逗号打印始终会打印尾随空格。

要么使用一个连接所有内容的打印语句,要么使用sys.stdout.write()直接写入终端而无需额外的空格:

print Fore.YELLOW + Style.BRIGHT + '[' + strftime("%H:%M:%S") + ']',

或者

sys.stdout.write(Fore.YELLOW + Style.BRIGHT + '[')
sys.stdout.write(strftime("%H:%M:%S"))
sys.stdout.write(']')

或使用字符串格式:

print '{Fore.YELLOW}{Style.BRIGHT}[{time}] {Style.BRIGHT}{Fore.RED} Name {Fore.BLACK}| {Fore.WHITE}{Style.DIM}Hello!'.format(
    Style=Style, Fore=Fore, time=strftime("%H:%M:%S"))
于 2013-08-01T21:26:16.967 回答
1

另一种选择是使用end=""print() 选项。这不会打印换行符,也不会在末尾添加额外的空间。

print(Style.BRIGHT + Fore.RED + ' Name', end="")
print(Fore.BLACK + '|', end="")
print(Fore.WHITE + Style.DIM + 'Hello!')

需要注意的是,该end选项仅适用于 Python 3。如果您在 Python 2.6-ish 中也可用from __future__ import print_function

于 2013-08-01T23:00:22.763 回答