如何处理十进制和千位分隔符的逗号

问题描述 投票:0回答:1

由于这里不重要的原因,我有一个excel表格,其中我的数字有小数点的逗号以及数千个分隔符。区分逗号应该是小数还是千位分隔符的唯一方法是逗号后面的位数:

decimal = 7,29
thousands = 23,767,209

我的方法,适用于我的情况,是将数字读入字符串并执行以下代码:

strings = ["0", "87,390,112", "78", "9,27", "1"]
strings_new = []

for i in strings:
    if len(i) >= 3:
        # check if third last char is a comma --> decimal
        if i[-3] == ',':
            i = i[:-3] + '.' + i[-3 + 1:]              
    if len(i) >= 4:
        # check if fourth last char is a comma --> all commas are thousands
        if i[-4] == ',':
            i = i.replace(",", "")

    strings_new.append(i)

strings_new = [float(i) for i in strings_new]

输出看起来很好:

strings_new = [0.0, 87390112.0, 78.0, 9.27, 1.0]

是否有任何特殊情况,我没有想到这个代码?是否有更有效的方法来解决这个问题?

python string formatting decimal-point
1个回答
1
投票

两种情况:

  1. 如果小数只有一位数:100,1。使用i.rfind(',')获取逗号位置,而不是使用-3对其进行硬编码。
  2. 如果它包含两个条件:10,000,24。它将通过第二个if子句(10,000.24)。总是在没有if子句的情况下运行i.replace(",", "")应该没问题。
© www.soinside.com 2019 - 2024. All rights reserved.