在python中couting一组单词

时间:2018-01-22 16:33:00

标签: python-3.x

假设s是一个小写字符串。

编写一个程序,打印字符串' bob'发生在s。例如,如果s =' azcbobobegghakl',那么您的程序应该打印

bob发生的次数是:2

这是我的答案,但我不知道我的代码有什么问题。请帮忙

s = "azcbobobegghakl"
coutBob=0
i=0
for char in range (len(s)):
    if char[i:i+3]=="bob":
        coutBob+=1
    else:
        i=i+1
print ("Number of times bob occurs is: " + str(coutBob))

2 个答案:

答案 0 :(得分:0)

您需要下标字符串s,而不是索引:

for i in range(len(s)):
    if s[i:i+3]=="bob":
        coutBob+=1

答案 1 :(得分:0)

我认为这会对你有帮助。

#include <iostream>
#include <iomanip>
#include <sstream>
#include <cstdlib>
#include <stdexcept>

int hex2dec(const std::string& value)
{
    int result{-1};
    try
    {
        result = std::stol(value, nullptr, 16); ///< base 16 hex
    }
    catch (std::invalid_argument e)
    {
        std::cout << "Invalid argument" << std::endl;
    }
    catch (std::out_of_range e)
    {
        std::cout << "Out of range" << std::endl;
    }
    return result;
}

std::string dec2hex(const int value)
{
    std::string result;
    std::stringstream ss;
    ss << std::hex << "0x" << value;
    ss >> result;
    return result;
}

int main()
{
    int choice{0};
    do
    {
        std::cout << "What would you like to do? (Enter number)" << std::endl;
        std::cout << "1) Decimal to hexadecimal conversion" << std::endl;
        std::cout << "2) Hexadecimal to decimal conversion\n-> " << std::flush;
        while (!(std::cin >> choice))
        {
            std::cout << "-> ";
            std::cin.clear();
            std::cin.ignore(256, '\n');
        }
        if (choice == 1)
        {
            std::cout << "Enter the decimal number to convert\n-> " << std::flush;
            int number{0};
            while (!(std::cin >> number))
            {
                std::cout << "-> ";
                std::cin.clear();
                std::cin.ignore(256, '\n');
            }
            std::cout << "Answer in base 16: " << dec2hex(number) << std::endl;
        }
        else if (choice == 2)
        {
            std::cout << "Enter the hexadecimal number to convert\n-> " << std::flush;
            std::string str;
            std::cin >> str;
            std::cout << "Answer in base 10: " << hex2dec(str) << std::endl;
        }
        std::cout << std::endl;
    }
    while (choice == 1 || choice == 2);

    return 0;
}