15-7数字字符串格式化

问题描述

小M在工作时遇到了一个问题,他需要将用户输入的不带千分位逗号的数字字符串转换为带千分位逗号的格式,并且保留小数部分。小M还发现,有时候输入的数字字符串前面会有无用的 0,这些也需要精简掉。请你帮助小M编写程序,完成这个任务。


测试样例

样例1:

输入:s = "1294512.12412"

输出:'1,294,512.12412'

样例2:

输入:s = "0000123456789.99"

输出:'123,456,789.99'

样例3:

输入:s = "987654321"

输出:'987,654,321'

python 复制代码
def solution(s: str) -> str:
    # 先处理字符串,移除前导零
    # 使用 lstrip('0') 移除前面的零
    # 如果移除后为空字符串,说明输入的是 "0" 或 "0.00" 等情况,设置为 "0"
    stripped_s = s.lstrip('0') or '0'

    # 查找小数点的位置
    if '.' in stripped_s:
        integer_part, decimal_part = stripped_s.split('.')
    else:
        integer_part, decimal_part = stripped_s, ''
    
    # 格式化整数部分,使用 format 函数和千分位格式
    # 将整数部分转为千分位形式
    formatted_integer_part = f"{int(integer_part):,}"

    # 组装最终的结果
    if decimal_part:
        result = f"{formatted_integer_part}.{decimal_part}"
    else:
        result = formatted_integer_part

    return result

if __name__ == '__main__':
    # 测试用例
    print(solution("1294512.12412") == '1,294,512.12412')  # 输出: True
    print(solution("0000123456789.99") == '123,456,789.99')  # 输出: True
    print(solution("987654321") == '987,654,321')  # 输出: True
相关推荐
进击的明明1 天前
当AI开始“边想边干”:深入聊聊ReAct,以及如何用Python手搓一个简单Agent
python·面试·agent
全栈弄潮儿1 天前
Python实战第8期:函数
后端·python·编程语言
zyl7651 天前
FlashAttention 详解:从 GPU 硬件、普通 Attention 到分块计算与 Online Softmax
算法
卷无止境1 天前
暗流与破局:AI时代的代码安全审查工具全景指南
后端·python
卷无止境1 天前
一人公司的全栈选型指南:让 AI Agent 写得快,也让生意跑得稳
后端·python
爱读书的小胖1 天前
LeetCode 122:买卖股票的最佳时机 II(C)解题分析
算法
结局无敌1 天前
React Native for OpenHarmony 实战:三方库 react-native-modal-dialog 的鸿蒙化适配指南
深度学习·算法·react native·react.js·harmonyos
滴啦嘟啦哒1 天前
【具身笔记】【π0.5 微调与仿真】五、在MuJoCo中实现可视化仿真
笔记·python·vla·具身
OPEN-F1 天前
ROS2系列教程:上位机建图与导航(原理综合)
算法·机器人
weixin_307779131 天前
C++代码实现MATLAB中的fitrtree函数功能
开发语言·c++·算法·matlab