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

Python中如何在字符串内原地对数字保留两位小数

Python 处理字符串内数字并保留两位小数

可以通过正则表达式匹配字符串中的数字,结合自定义处理函数实现原地保留两位小数(自动四舍五入)的需求,以下是具体实现:

完整代码示例

import re

def format_decimals_in_string(input_str):
    def process_number(match):
        # 将匹配到的数字字符串转为浮点数
        num = float(match.group())
        # 格式化保留两位小数,自动完成四舍五入
        return "{:.2f}".format(num)
    
    # 正则匹配所有数字(支持整数、小数,如需兼容负数可改为 r'-?\d+\.?\d*')
    return re.sub(r'\d+\.?\d*', process_number, input_str)

# 测试示例
sample_input = "The values in this string are 245.783634 and the other value is: 25.21694"
sample_output = format_decimals_in_string(sample_input)
print(sample_output)

代码说明

  • 正则表达式:r'\d+\.?\d*' 可以匹配字符串中的整数(如 123)和小数(如 245.783634);如果需要处理负数,只需修改为 r'-?\d+\.?\d*'。
  • 处理逻辑:process_number 函数将匹配到的数字字符串转为浮点数,通过 "{:.2f}" 格式化语法实现保留两位小数,同时自动完成四舍五入。
  • 替换操作:re.sub() 函数会遍历字符串,将所有匹配到的数字替换为处理后的结果,最终返回修改后的完整字符串。

输出结果

运行代码后,输入字符串会被处理为:

"The values in this string are 245.78 and the other value is: 25.22"

内容的提问来源于stack exchange,提问作者Drthm1456

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 14:50:13