Python函数返回值打印格式问题:如何去除元组括号并格式化输出
解决方法
原代码返回的是元组,导致print输出带括号的格式。要得到连贯的字符串输出,需将返回值改为单一字符串,以下是几种可行方案:
方案1:使用f-string(推荐,Python3.6+)
def icecream(): cost = 6 # 无需int(6),直接赋值整数即可 flavor = input('What flavor would you like? => ') return f'The {flavor} will cost {cost} dollars.' print(icecream())
f-string会自动将变量嵌入字符串并完成类型转换,返回完整的目标字符串,print后直接输出期望格式。
方案2:使用str.join()方法
def icecream(): cost = 6 flavor = input('What flavor would you like? => ') # 所有元素转字符串后用空格拼接 return ' '.join(['The', flavor, 'will cost', str(cost), 'dollars.']) print(icecream())
通过str.join()将字符串列表用空格连接,注意需把整数cost转为字符串类型。
方案3:使用%格式化操作符
def icecream(): cost = 6 flavor = input('What flavor would you like? => ') return 'The %s will cost %d dollars.' % (flavor, cost) print(icecream())
通过占位符%s(字符串)和%d(整数)将变量填充到模板字符串中,生成完整输出内容。
内容的提问来源于stack exchange,提问作者SorryBoutThatEh
相关产品推荐
相关产品推荐

