You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python函数返回含变量的字符串时如何去除多余特殊字符

Python函数返回含变量的字符串时如何去除多余特殊字符

嘿,问题出在你return的方式上哦!你现在用逗号把多个值分开返回,Python会自动把它们打包成一个元组,所以打印的时候才会出现括号、逗号这些元组的格式符号。咱们只需要让函数返回一个完整的字符串,就能解决这个问题啦,给你几种简单好用的方法:

1. 使用f-string(Python 3.6+最推荐)

这是目前最简洁直观的写法,可读性拉满,直接在字符串里嵌入变量就行:

def area_of_triangle(bottom, height):
    area = 0.5 * bottom * height
    return f'The area of a triangle with a bottom of {bottom} and a height of {height} is {area}.'

用f开头的字符串,把变量放在{}中,Python会自动帮你把变量转换成字符串并拼接成完整句子,打印出来完全符合你的预期。

2. 使用str.format()方法

如果你的Python版本低于3.6,这个方法兼容性更好:

def area_of_triangle(bottom, height):
    area = 0.5 * bottom * height
    return 'The area of a triangle with a bottom of {} and a height of {} is {}.'.format(bottom, height, area)

字符串里的{}是占位符,后面通过format()方法按顺序传入变量,同样能生成完整的目标字符串。

3. 字符串拼接(不推荐,可读性差)

虽然能实现需求,但需要手动把每个数字转成字符串,代码会比较繁琐:

def area_of_triangle(bottom, height):
    area = 0.5 * bottom * height
    return 'The area of a triangle with a bottom of ' + str(bottom) + ' and a height of ' + str(height) + ' is ' + str(area) + '.'

这种方式用+拼接字符串,但数字必须用str()转换类型,变量多的时候代码会显得很乱,所以一般不推荐使用。

现在你再调用print(area_of_triangle(2, 1)),就能得到你想要的输出:

The area of a triangle with a bottom of 2 and a height of 1 is 1.0.

备注:内容来源于stack exchange,提问作者Icode15promax

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.13 19:13:06