python - 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()
任何帮助,将不胜感激
解决方案
有几种方法可以做到这一点 - 但由于您使用自己的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)
推荐阅读
- lua - 如何理解 rename{ old = "temp.lua", new = "temp1.lua" }?
- javascript - 如果我用 AJAX 加载 php 文件,我的函数内容返回 [object HTMLDivElement]
- azure - Azure Log Analytics 查询返回 0 条记录权限问题?
- angular - Ionic 4 - 如何将 id 参数传递到另一个页面并从外部 api 检索 id 的数据
- c++ - 在 ubuntu16.04 上生成运行时犰狳库时出错
- ios - 饼图(iOS 图表)未显示在自定义 tableviewcell 中
- mongodb - 如何对整个文档中的字段进行求和以及搜索?
- python - 加载预训练模型时面临的问题
- listener - 事件监听器教程中的错误代码
- c# - 在 WPF 中并通过使用 Prism,如何使用 MouseButtonEventArgs 作为窗口命令的参数?