因此,我试图将用户输入的中间名切开并打印出来,但是它不起作用,我不知道该怎么做。
我已经尝试过查找
name_amount = int(input("How many names do you have? "))
namelist = []
index = 0
for i in range (name_amount):
name = input("Name: ")
namelist.append(name)
index += 1
print "You have " + str (name_amount) + " names."
print "Middle names: " + namelist[0][1:index - 1]
例如,如果您说您有3个名字,然后说L,然后T,然后K,我想说
Middle names: T
但是它只是说:
Middle names:
然后没有其他内容。
答案 0 :(得分:0)
为什么不只是:
name_amount = int(input("How many names do you have? "))
namelist = []
index = 0
for i in range (name_amount):
name = input("Name: ")
namelist.append(name)
index += 1
print "You have " + str (name_amount) + " names."
try:
print "Middle names: " + namelist[1]
except:
print "No middle names found"
更改:
print "Middle names: " + namelist[0][1:index - 1]
收件人:
try:
print "Middle names: " + namelist[1]
except:
print "No middle names found"
就是这样,它将起作用...
答案 1 :(得分:0)
您应该进行更改以返回列表中的第二个元素,并添加一个健全性检查,以发现是否首先输入了两个以上的名称。
name_amount = int(input("How many names do you have? "))
namelist = []
index = 0
for i in range (name_amount):
name = input("Name: ")
namelist.append(name)
index += 1
print "You have " + str (name_amount) + " names."
# Checking if at least 2 names are entered
if name_amount > 2:
print "Middle names: " + namelist[1]
else:
print "Could not find a middle name"