簡體   English   中英

python 中的異常處理計算字符串中的字符數

[英]Exception handling in python Counting the number of characters in a string

這是我的代碼。

def word_count(my_string):
    count=1
    if type(my_string) == str:
        try:
            for eachCharacter in my_string:
                if eachCharacter==' ':
                    count+=1
            return count
        except:
            return "Not a string"

我必須得到 output 為:

Word Count: 4
Word Count: 1
Word Count: 7
Word Count: Not a string
Word Count: Not a string
Word Count: Not a string

但我得到:

Word Count: 4
Word Count: 1
Word Count: 7
Word Count: None
Word Count: None
Word Count: None

誰能幫我找到這個錯誤

Изучите enumerate([1, 2, ...]) 和 raise Exeption("...")

您需要處理輸入不是字符串的情況:

def word_count(my_string):
    count=1
    if type(my_string) == str:
        for eachCharacter in my_string:
            if eachCharacter==' ':
                count+=1
        return count
    return "Not a string"

正如您現在所擁有的,您的 function 不會顯式返回任何內容,因此如果傳入的 object 不是字符串,則返回None 此外,try/except 對你沒有好處,因為try中的代碼永遠不會拋出異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM