python 2.7

时间:2018-03-24 18:28:37

标签: python python-2.7

我坚持这个任务。我有一个任务,我需要在python 2.7中编写一个程序,它提示用户输入一个字符串,然后程序需要返回该字符串中字母出现的次数。例如," google.com"必须返回' o' 3,':2,'。':1,' e':1,&#39 ; l':1,' m':1,' c':1

我知道我需要使用list()函数,但到目前为止我只有:

   string = raw_input("Enter a string: ")
   newString = list(string)

然后我被困在那里因为我不知道如何让程序计算字母出现的次数。我知道语法中必须有一个for循环,但我不确定在这种情况下我将如何使用它。 NB:我们还没有被引入字典或进口,所以请尽量保持简单。基本上最圆的方法将最有效。

2 个答案:

答案 0 :(得分:1)

您可以在string = raw_input("Enter a string: ") count_dict = {} for x in string: count_dict[x] = string.count(x) print count_dict #input : google.com # output : {'c': 1, 'e': 1, 'g': 2, 'm': 1, 'l': 1, 'o': 3, '.': 1} 函数的帮助下直接处理此问题。

您可以从空的dictonary开始,将输入的字符串的每个字符及其计数添加到字典中。

这可以这样做..!

webpack.config.js

答案 1 :(得分:0)

更新: 由于您尚未介绍字典和导入,因此可以使用以下解决方案。

for i in set(string):
print("'{}'".format(i), string.count(i), end=",")

使用计数器:

from collections import Counter
string = "google.com"
print(Counter(string))

其他方式,创建一个字典并添加循环遍历字符串的字符。

dicta = {}
for i in string: 
    if i not in dicta:
        dicta[i] = 1
    else: 
        dicta[i] += 1
print(dicta)