如何让我的代码返回答案而不需要额外的''和()

时间:2017-09-30 16:50:39

标签: python python-3.x

如何在没有额外''()的情况下让我的代码返回答案?

def analyze_text(text):
    #removes all of the non-al charaters
    new_string = ""
    for eachLetter in text:
        if eachLetter.isalpha():
            new_string += eachLetter
    #count the number of e
    text_count_E = text.count("E")
    text_count_e = text.count("e")
    total_e = text_count_E + text_count_e
    #gets the percentage of e
    percentage = 100 * total_e / len(new_string)

    return "The text contains ",len(new_string),"alphabetic characters, of 
    which",total_e,"(",percentage,")","are 'e'"

2 个答案:

答案 0 :(得分:0)

您返回了一个元组,而不是单个字符串

尝试仅返回必要的值,然后打印输出

return len(new_string), total_e

在功能之外,

new_len, total_e = analyze_text(text)
percent = 100 * total_e / new_len

print( "The text contains {} alphabetic characters, of which {} ({}) are 'e'".format(new_len, total_e, percent)) 

答案 1 :(得分:0)

请在下次提供更易读的代码。

您可以简单地使用每个字符串对象都可以执行的format()方法。 这可能会有所帮助。 https://pyformat.info/#simple

在你的情况下,它将是这样的:

return "The text contains {} alphabetic characters, of which {} ({}) are 'e'".format(len(new_string), total_e, percentage)