Skip to main content
 首页 » 编程设计

python之计算以字符开头的单词

2025年05月04日15pander-it

Write a function that accepts a string and a character as input and returns the count of all the words in the string which start with the given character. Assume that capitalization does not matter here. You can assume that the input string is a sentence i.e. words are separated by spaces and consists of alphabetic characters.

这是我的代码:

def count_input_character (input_str, character): 
    input_str = input_str.lower() 
    character = character.lower() 
    count = 0 
    for i in range (0, len(input_str)): 
        if (input_str[i] == character and input_str[i - 1] == " "): 
            count += 1 
    return (count) 
 
 
 
#Main Program 
input_str = input("Enter a string: ") 
character = input("Enter character whose occurances are to be found in the given input string: ") 
result = count_input_character(input_str, character) 
#print(result) 

这里唯一缺少的部分是如何检查句子的第一个单词是否是用户给定的字符。考虑这个输出:

Your answer is NOT CORRECT Your code was tested with different inputs. > For example when your function is called as shown below:

count_input_character ('the brahman the master of the universe', 't')

####### Your function returns ############# 2 The returned variable type is: type 'int' ### Correct return value should be ######## 3 The returned variable type is: type 'int'

请您参考如下方法:

你的函数错过了第一个 t 因为在这一行

if (input_str[i] == character and input_str[i - 1] == " "): 

当 i 为 0 时,input_str[i - 1] 为 input_str[-1] Python 将解析为字符串的最后 字符!

要解决此问题,您可以将条件更改为

if input_str[i] == character and (i == 0 or input_str[i - 1] == " "): 

或者使用str.split具有列表理解力。或者 regular expression比如r'(?i)\b%s'​​,其中(?i)表示“忽略大小写”,\b是单词边界和 %s 字符的占位符..