【问题标题】:Annoying spaces that won't disappear. What should I do?不会消失的烦人空间。我该怎么办?
【发布时间】:2013-08-03 00:20:35
【问题描述】:

我目前正在使用 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!

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

非常感谢我能得到的所有帮助!谢谢。

【问题讨论】:

    标签: python string text colorama


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

      要么使用 one 打印语句将所有内容连接起来,要么使用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"))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-25
        • 2010-09-14
        • 2021-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多