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
相关推荐
好好学习啊天天向上5 小时前
C盘容量不够,python , pip,安装包的位置
linux·python·pip
时见先生5 小时前
Python库和conda搭建虚拟环境
开发语言·人工智能·python·自然语言处理·conda
二十雨辰5 小时前
[python]-循环语句
服务器·python
Yvonne爱编码6 小时前
Java 四大内部类全解析:从设计本质到实战应用
java·开发语言·python
wqwqweee6 小时前
Flutter for OpenHarmony 看书管理记录App实战:搜索功能实现
开发语言·javascript·python·flutter·harmonyos
tobias.b7 小时前
408真题解析-2010-7-数据结构-无向连通图
数据结构·算法·图论·计算机考研·408真题解析
-To be number.wan7 小时前
Python数据分析:numpy数值计算基础
开发语言·python·数据分析
良木生香8 小时前
【鼠鼠优选算法-双指针】003:快乐数 & 004:盛水最多的容器
算法
Cx330❀8 小时前
【优选算法必刷100题】第41-42题(模拟):Z 字形变换,外观数列
c++·算法
沃尔特。8 小时前
直流无刷电机FOC控制算法
c语言·stm32·嵌入式硬件·算法