我正在制作这个由我的学校提供给我的程序,它是用ASCII文本艺术写出你自己的名字,但这只是复制和粘贴。我试图让它用户输入一个输入,然后输出他们的名字。我的程序目前有效,但它不会停留在一条线上。
我的代码:
name = input("What is your name: ")
splitname = list(name)
for i in range(len(splitname)):
f=open(splitname[i] + ".txt","r")
contents = f.read()
print(contents)
如果可能的话,我想把它全部放到一行,我该怎么做?
解决方案有点复杂,因为您必须逐行打印,但您已经需要'letter'文件的所有内容。
解决方案是读取第一个字母的第一行,然后将此字符串与下一个字母的第一行连接,依此类推。然后对第二行执行相同操作,直到您打印所有行。
我不会提供完整的解决方案,但我可以帮助修复您的代码。首先,你必须只阅读一行字母文件。您可以使用f.readline()
而不是f.read()
执行此操作,如果句柄仍处于打开状态,则此函数的每次连续调用都将读取此文件中的下一行。
要一个接一个地打印ASCII字母,您必须将字母分成多行并连接所有相应的行。假设您的ASCII文本由8行组成:
name = input("What is your name: ")
splitname = list(name)
# Put the right number of lines of the ASCII letter
letter_height = 8
# This will contain the new lines
# obtained concatenating the lines
# of the single letters
complete_lines = [""] * letter_height
for i in range(len(splitname)):
f = open(splitname[i] + ".txt","r")
contents = f.read()
# Split the letter in lines
lines = contents.splitlines()
# Concatenate the lines
for j in range(letter_height):
complete_lines[j] = complete_lines[j] + " " + lines[j]
# Print all the lines
for j in range(letter_height):
print(complete_lines[j])