I'm trying to print a list of names and their corresponding index number each on a new line. This is my current code:
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))
and current output:
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
How do I code it so that each name prints like this:
1. Tyler
2. Gemma
3. Alex
You split
it to count the words, but didn't keep the split version to iterate by word. Simple solution is to change:
nameList = input("Enter 3 names: ")
wordCount = len (nameList.split(' '))
to:
# Store list of names, not single string
nameList = input("Enter 3 names: ").split(' ')
wordCount = len(nameList)
You can do this simpally:
a=input().split()
j=1
for i in a:
print(str(j)+". "+i)
j+=1
Output:
1. Tyler
2. Gemma
3. Alex
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.