编写程序来计算名称中的字母

时间:2014-03-29 19:46:26

标签: python

  

编写一个完整的Python程序,要求用户输入他们的名字,然后程序将输出该名称中的字符数,然后将每个字母计数到最后。

当我运行程序时,我希望它看起来像这样:

Please enter your name: Micheal
Your name has 7 characters in it

The 1 letter in  your name is M
The 2 letter in your name is i
The 3 letter in your name is c 
The 4 letter in your name is h
The 5 letter in your name is e
The 6 letter in your name is a 
the 7 letter in your name is l

我需要这个程序的代码,并且当你输入任何名字时程序应该能够运行。我已经知道如何输入名称并使用len函数来计算名称中有多少个字符,但我无法弄清楚如何进行其余的操作。我正在使用python版本2.7.6 for windows所以我想要根据这个版本的代码。

这就是我所拥有的:

name=raw_input("Please enter your name: ")
print

print"Your name has", len(name),"characters in it"
print

for char in name:
    print char

2 个答案:

答案 0 :(得分:2)

要获取可迭代中每个元素的值和索引,请使用enumerate()。这个内置函数接受每个元素及其索引,将每个元素作为tuple放入list

演示:

>>> for index, char in enumerate(name):
...     print('The {} item in your name is {}'.format(i+1, item))
... 

The 1 item in your name is M
The 2 item in your name is i
The 3 item in your name is c
The 4 item in your name is h
The 5 item in your name is a
The 6 item in your name is e
The 7 item in your name is l

答案 1 :(得分:0)

我认为你正在寻找the enumerate function

enumerate将一个可迭代对象(如字符串)作为其参数,并返回一个产生index, item元组的迭代器。 enumerate("Michael")会产生(0, "M"), (1, "i"), (2, "c")等等,这似乎几乎完全符合您的要求(如果您不想从索引零开始,则可以传递start值)。您可以使用for index, char in enumerate(name, start=1):在循环中解压缩元组值。

另一个建议是使用str.format来准备输出,而不是仅在print语句中使用逗号将项目链接在一起。您可能想要"The {} letter in your name is {}".format(index, char)或类似的东西。