Python:将返回语句中的元组转换为字符串
我一直在研究HTTLC,完成这个问题有点困难 解决问题不是什么大问题,但我很难将结果作为字符串而不是元组数据类型返回 这是我的密码:Python:将返回语句中的元组转换为字符串,python,return,tuples,Python,Return,Tuples,我一直在研究HTTLC,完成这个问题有点困难 解决问题不是什么大问题,但我很难将结果作为字符串而不是元组数据类型返回 这是我的密码: def wordCount(paragraph): splited = paragraph.split() wordnum = len(splited) eWord = [] for aWord in splited: if "e" in aWord: eWord.append(aWord)
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输出('yourtextcontains',108',words,其中,'50',(',46.3',%)',“containmentane.”
,它是元组,而不是字符串
我知道我可以把print放在函数的末尾,不使用print()语句调用函数,但如何用return语句解决这个问题呢
return "Your text contains %s words, of which %s (%s%%) contains an 'e'." % (wordnum, eWordnum, percent)
或
在第一种情况下,您执行字符串连接,并且必须将wordnum
、eWordnum
和其他数值变量转换为str
(通过执行str(variableName)
)以允许连接(并且没有运行时错误)
在第二种情况下,执行字符串替换,这意味着您给出某种“占位符”%s
(这意味着字符串),并用%
符号后面的元组参数替换它们
如果通过
返回分隔的内容,
将返回一个元组(如您所见)这是因为在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)
for循环可能会起作用,但您必须格式化字符串以向其添加空格
for item in tuplename: print item,
请确保在项目后保留逗号,因为这会将其打印在同一行上。尝试以下操作:
return "Your text contains {0} words, of which {1} ({2}%) contains an 'e'.".format(wordnum,eWordnum,percent)
return "Your text contains %(wordnum)s words, of which %(ewordnum)s (%(percent)s %%), contains an 'e'."%locals()
使用%(变量名)s
通常更容易维护。这个怎么样
return "Your text contains " + wordnum + " words, of which " + eWordnum + " (" + percent + "%) " + " contains an 'e'."
将逗号替换为“+”,这应该会起作用。+1,最佳答案,因为它不只是给出答案,而是解释了错误否,它不会起作用,因为您缺少整数和字符串到串联过程的转换
return "Your text contains {0} words, of which {1} ({2}%) contains an 'e'.".format(wordnum,eWordnum,percent)
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))
return "Your text contains %(wordnum)s words, of which %(ewordnum)s (%(percent)s %%), contains an 'e'."%locals()
return "Your text contains " + wordnum + " words, of which " + eWordnum + " (" + percent + "%) " + " contains an 'e'."