首页 > 解决方案 > Python - 如何在使用打字机效果时居中对齐文本

问题描述

第一次在这里发帖,所以我为任何错误的格式等道歉。

我对编码很陌生,我正在使用 Python 进行基于文本的冒险。它工作正常,但我想居中对齐我的所有文本。我在网上查了一下,找到了 center(width) 函数。但是,我正在使用一个函数,该函数使用打字机效果键入字符串,如果我在字符串中的文本之前添加有意的空格,即使空格也会产生我不想要的打字机效果。

我希望我的文本开始在我的窗口中心打印。有没有办法用一个已经应用了函数的字符串来做到这一点?下面的代码:


import sys
import time

def typewriter(message):

    for char in message:
        sys.stdout.write(char)
        sys.stdout.flush()
        time.sleep(0.04)

def character_info():
    message = "Before we start, please enter your name below :\n"
    typewriter(message)
    input("\n>>> ")


character_info()

任何帮助,将不胜感激

标签: python

解决方案


有几种方法可以做到这一点 - 但由于您使用自己的typewriter代码,其中一种更简单的方法就是忽略前导空格:


import sys
import time

def typewriter(message):
    started = False
    for char in message:
        sys.stdout.write(char)
        sys.stdout.flush()
        if char != " ":
            started = True
        if started:
            time.sleep(0.04)

要在打印最后一个字符后立即返回代码,一件简单的事情是在遍历字符之前去除字符串右侧的所有空格:


import sys
import time

def typewriter(message):
    message = message.rstrip()
    started = False
    for char in message:
        sys.stdout.write(char)
        sys.stdout.flush()
        if char != " ":
            started = True
        if started:
            time.sleep(0.04)


推荐阅读