在“级联"中打印用户输入字符? [英] Print user input in "cascade" of characters?
问题描述
我正在尝试创建代码来收集用户的名字和姓氏(输入顺序是最后一个,第一个)并以级联方式先打印,最后打印:
J○Hn秒米一世吨H
我真的很接近,但我不喜欢我的代码的工作方式.我认为有一种更简单的方法,而且我也遇到了一些问题IndexError:如果我输入的名称比我输入的打印语句的数量长,则字符串索引超出范围.有什么想法吗?
这是我的代码:
last = raw_input('请输入您的姓氏:')first= raw_input('请输入您的名字:')打印(第一[0])打印('\t' + 第一个[1])print('\t'*2 + first[2])打印('\t'*3+first[3])打印('\t'*4+first[4])打印('\t'*5+第一个[5])打印('\t'*6+第一个[6])打印(最后[0])打印('\t' + 最后[1])print('\t'*2 + last[2])打印('\t'*3+last[3])打印('\t'*4+last[4])打印('\t'*5+last[5])
您可以编写一个通用函数,如下所示,并重用于您的字符串.
def 级联名称(名称):对于 i, c in enumerate(name):打印 '\t'*(i+1), c
输出:
<预><代码>>>>级联名称(富")F○○在你的情况下,你会这样做:
last = raw_input('请输入您的姓氏:')first= raw_input('请输入你的名字:')级联名称(最后)级联名称(第一个)
I am trying to create code that gathers a user's first and last name (input order is last, first) and prints it first, last in a cascading way:
J
o
h
n
S
m
i
t
h
I'm really close, but I don't like the way my code works. I think there's an easier way, and I'm also running into issues where I get IndexError: string index out of range if I put in a name that is longer than how many print statements I put in. Any ideas?
here's my code:
last = raw_input('enter your last name:')
first= raw_input('enter your first name:')
print(first[0])
print('\t' + first[1])
print('\t'*2 + first[2])
print('\t'*3+first[3])
print('\t'*4+first[4])
print('\t'*5+first[5])
print('\t'*6+first[6])
print(last[0])
print('\t' + last[1])
print('\t'*2 + last[2])
print('\t'*3+last[3])
print('\t'*4+last[4])
print('\t'*5+last[5])
You can write a generic function, like the one shown below and reuse for your strings.
def cascade_name(name):
for i, c in enumerate(name):
print '\t'*(i+1), c
output:
>>> cascade_name("foo")
f
o
o
In your case you would do:
last = raw_input('enter your last name:')
first= raw_input('enter your first name:')
cascade_name(last)
cascade_name(first)
这篇关于在“级联"中打印用户输入字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!