我试图在新行上打印一个名单及其对应的索引号。这是我目前的代码:
nameList = input("Enter 3 names: ")
wordCount = len (nameList.split(' '))
print ("Your list contains", wordCount, "names.")
for index, element in enumerate(nameList, start=1):
print("{}: {}".format(index, element))
和当前输出:
Enter 3 names: Tyler Gemma Alex
Your list contains 3 names.
1: T
2: y
3: l
4: e
5: r
6:
7: G
8: e
9: m
10: m
11: a
12:
13: A
14: l
15: e
16: x
如何对其进行编码,以便每个名称的打印方式如下:
1. Tyler
2. Gemma
3. Alex
答案 0 :(得分:1)
你split
计算单词,但不保持拆分版本按字迭代。简单的解决方案是改变:
nameList = input("Enter 3 names: ")
wordCount = len (nameList.split(' '))
为:
# Store list of names, not single string
nameList = input("Enter 3 names: ").split(' ')
wordCount = len(nameList)
答案 1 :(得分:0)
你可以简单地做到这一点:
a=input().split()
j=1
for i in a:
print(str(j)+". "+i)
j+=1
输出:
1. Tyler
2. Gemma
3. Alex