2

我一直在研究 HTTLCS,但在解决问题时遇到了一些困难。

解决问题并不是什么大问题,但是我无法将结果作为字符串而不是元组数据类型返回。

这是我的代码:

def wordCount(paragraph):
    splited = paragraph.split()
    wordnum = len(splited)
    eWord = []
    for aWord in splited:
        if "e" in aWord:
            eWord.append(aWord)
    eWordnum = len(eWord)
    percent = round(eWordnum / wordnum * 100,2)
    return "Your text contains", wordnum, "words, of which" , eWordnum , "(" , percent , "%)" , "contains an 'e'." 



print(wordCount(p))

Python 输出('Your text contains', 108, 'words, of which', 50, '(', 46.3, '%)', "contains an 'e'.")的是一个元组,而不是一个字符串。

我知道我可以将 print 放在函数的末尾并在没有 print() 语句的情况下调用函数,但是如何使用 return 语句解决这个问题?

4

8 回答 8

8

这是因为您在 return 语句中使用了逗号,Python 将其解释为元组。尝试format()改用:

def wordCount(paragraph):
    splited = paragraph.split()
    wordnum = len(splited)
    eWord = []
    for aWord in splited:
        if "e" in aWord:
            eWord.append(aWord)
    eWordnum = len(eWord)
    percent = round(eWordnum / wordnum * 100,2)
    return "Your text contains {0} words, of which {1} ({2}%) contains an 'e'".format(wordnum, eWordnum, percent)

>>> wordCount("doodle bugs")

"Your text contains 2 words, of which 1 (0.0%) contains an 'e'"
于 2012-06-07T15:10:51.623 回答
1
return "Your text contains %s words, of which %s (%s%%) contains an 'e'." % (wordnum, eWordnum, percent)
于 2012-06-07T15:09:35.033 回答
1
return "Your text contains " + str(wordnum) + 
       " words, of which " + str(eWordnum) + 
       " (" + str(percent) +  "%)" + " contains an 'e'."

或者

return "Your text contains %s words, of which %s (%s%%) contains an 'e'." 
        % (wordnum, eWordnum, percent)

在第一种情况下,您进行字符串连接wordnum,并且必须将eWordnum和其他数字变量转换为str(通过执行str(variableName))以允许连接(并且没有运行时错误)

在第二种情况下,您进行字符串替换,这意味着您给出某种“占位符” %s(即字符串),然后用%符号后面的元组参数替换它们

如果您返回单独的东西,,您将返回一个元组(如您所见)

于 2012-06-07T15:10:09.793 回答
1
return "Your text contains {0} words, of which {1} ({2}%) contains an 'e'.".format(wordnum,eWordnum,percent) 
于 2012-06-07T15:12:12.277 回答
0

for 循环可能会起作用,但您必须格式化字符串以向它们添加空格。

for item in tuplename: print item,

确保在项目后保留逗号,因为这会将其打印在同一行。

于 2012-06-07T15:11:44.703 回答
0
def wordCount(paragraph):
    splited = paragraph.split()
    wordnum = len(splited)
    eWord = []
    for aWord in splited:
        if "e" in aWord:
            eWord.append(aWord)
    eWordnum = len(eWord)
    percent = round(eWordnum / wordnum * 100,2)
    dummy =  "Your text contains {0} words, of which {1} {2} contains an 'e'.".format(wordnum,eWordnum, percent) 
    return dummy


print(wordCount(p))
于 2012-06-07T15:12:18.910 回答
0

试试这个 :

return "Your text contains %(wordnum)s words, of which %(ewordnum)s (%(percent)s %%), contains an 'e'."%locals()

使用%(variable_name)sas字符串格式通常更容易维护。

于 2012-06-07T15:12:21.000 回答
0

这个怎么样

return "Your text contains " + wordnum + " words, of which " + eWordnum + " (" + percent + "%) " + " contains an 'e'."

用“+”替换逗号,这应该可以。

于 2012-06-07T15:13:28.303 回答