Que*_*Quo 2 python tuples return
我一直在研究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))
Run Code Online (Sandbox Code Playgroud)
Python输出('Your text contains', 108, 'words, of which', 50, '(', 46.3, '%)', "contains an 'e'.")是一个元组,而不是字符串.
我知道我可以在函数的末尾放置print并在没有print()语句的情况下调用函数,但是如何使用return语句解决这个问题呢?
这是因为你在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)
Run Code Online (Sandbox Code Playgroud)
>>> wordCount("doodle bugs")
"Your text contains 2 words, of which 1 (0.0%) contains an 'e'"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2301 次 |
| 最近记录: |