Python:将一个元组从return语句转换为字符串

时间:2012-06-07 15:06:24

标签: python return tuples

我一直在研究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语句解决这个问题?

8 个答案:

答案 0 :(得分: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'"

答案 1 :(得分:1)

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

答案 2 :(得分: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)

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

在第二种情况下,你做一个字符串替换,这意味着你给了某种“占位符”%s(这意味着字符串),你用下面的元组参数替换它们%符号

如果你通过,单独返回一个元素,你将返回一个元组(如你所见)

答案 3 :(得分:1)

return "Your text contains {0} words, of which {1} ({2}%) contains an 'e'.".format(wordnum,eWordnum,percent) 

答案 4 :(得分:0)

for循环可能有效,但您必须格式化字符串以向其添加空格。

for item in tuplename: print item,

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

答案 5 :(得分: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))

答案 6 :(得分:0)

试试这个:

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

使用%(variable_name)s作为string formatting通常更容易维护。

答案 7 :(得分:0)

这个怎么样

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

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