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

Python字符串格式化求助:数字千分位与百分比两位小数处理

文本文件数据格式化解决方案

需求说明

读取指定txt文件,将数据格式化为目标字符串,需满足两个格式要求:

  • 第3、4列数字添加千分位分隔符(例如21820转换为21,820)
  • 最后一列格式化为带两位小数的百分比形式(例如104.3转换为104.30%)

示例格式化结果:

"The overall attendance at Bulls was 894659, average attendance was 21,820 and the capacity was 104.30%"

输入的txt文件内容

1   Bulls   894659  21820   104.3
2   Cavaliers   843042  20562   100
3   Mavericks   825901  20143   104.9
4   Raptors 812863  19825   100.1
5   NY_Knicks   812292  19812   100

原代码(功能基本正常,缺少格式化逻辑)

file_1 = open ('basketball.txt', 'r')
count = 0

list_1 = [ ]
for line in file_1:
    count += 1
    textline = line.strip()
    items = textline.split()
    list_1.append(items)

print('Number of teams: ', count)
for line in list_1:
    print ('Line: ', line)

file_1.close()

for line in list_1: #iterate over the lines of the file and print the lines with formatted strings
    a, b, c, d, e = line
    print (f'The overall attendance at the {b} game was {c}, average attendance was {d}, and the capacity was {e}%.')

修改后的代码(实现格式化要求)

file_1 = open('basketball.txt', 'r')
count = 0

list_1 = []
for line in file_1:
    count += 1
    textline = line.strip()
    items = textline.split()
    list_1.append(items)

print('Number of teams: ', count)
for line in list_1:
    print('Line: ', line)

file_1.close()

for line in list_1:
    a, b, c, d, e = line
    # 将字符串类型的数值转为对应数字类型
    total_attendance = int(c)
    avg_attendance = int(d)
    capacity = float(e)
    # 用f-string内置格式规则实现千分位和百分比格式化
    print(f'The overall attendance at the {b} game was {total_attendance:,}, average attendance was {avg_attendance:,}, and the capacity was {capacity:.2f}%.')

关键修改说明

  • 先将第3、4列的字符串转为整数,通过:,格式符自动添加千分位分隔符
  • 将最后一列的字符串转为浮点数,通过.2f格式符强制保留两位小数,直接拼接百分号完成百分比格式
  • 全程利用Python f-string的原生格式化能力,简洁实现需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:01:28