如何将字符串“1157903”转换为十进制“1.157903”

时间:2013-02-21 04:05:00

标签: python string decimal

我想知道如何将没有小数点的字符串转换为小数点,例如在python中将“1157903”转换为“1.157903”

感谢。

4 个答案:

答案 0 :(得分:4)

s = "1157903"
s2 = '{}.{}'.format(s[0],s[1:])

答案 1 :(得分:2)

更多方式:

>>> s = '115793'
>>> s[0] + '.' + s[1:]
'1.15793'

>>> s = '115793'
>>> '.'.join([s[0], s[1:]])
'1.15793'

根据您在问题中添加的评论进行更新:

from bisect import bisect

_METRIC_PREFIXES = [  # must be in ascending order for bisect
   ( 0,   ''),  # <blank>
   ( 1, 'da'),  #  deca
   ( 2,  'h'),  #  hecto
   ( 3,  'k'),  #  kilo
   ( 6,  'M'),  #  mega
   ( 9,  'G'),  #  giga
   (12,  'T'),  #  tera
   (15,  'P'),  #  peta
   (18,  'E'),  #  exa
   (21,  'Z'),  #  zetta
   (24,  'Y'),  #  yotta
]

_BREAKPOINTS = tuple(10.**item[0] for item in _METRIC_PREFIXES)

def format_numeric_string(s, prec=1):
    v = int(s)
    i = bisect(_BREAKPOINTS, v)-1
    d = _BREAKPOINTS[i]
    s = _METRIC_PREFIXES[i][1]
    return '{:.{prec}f}{suffix}'.format(v/d, suffix=s, prec=prec)

if __name__ == '__main__':
    import random
    randigit = lambda: random.choice('123456789')
    n_digit_string = lambda n: ''.join(d for _ in xrange(n) for d in randigit())

    for s in (n_digit_string(prefix[0]+1) for prefix in _METRIC_PREFIXES):
        print '{:,d} --> {}'.format(int(s), format_numeric_string(s))

不同长度随机数字字符串的示例输出:

3 --> 3.0
18 --> 1.8da
389 --> 3.9h
3,765 --> 3.8k
2,152,457 --> 2.2M
1,965,289,562 --> 2.0G
7,624,947,619,324 --> 7.6T
7,424,298,578,879,224 --> 7.4P
5,546,663,458,831,949,667 --> 5.5E
4,794,459,711,325,322,715,236 --> 4.8Z
9,992,885,249,921,967,199,174,883 --> 10.0Y

答案 2 :(得分:0)

"1.157903"不是小数,它是一个字符串。

您是要将字符串转换为数字,还是将数字的字符串表示形式转换为带小数的字符串?

如果是前者,那么:

>>> s = '115793'
>>> float(s) / 10 ** (len(s) - 1)
1.15793

否则:

>>> '{}.{}'.format(s[0], s[1:])
'1.15793'

避免复制字符串的另一种方法是使用bytearray

>>> ba = bytearray('12345')
>>> ba.insert(1, ord('.'))
>>> ba
bytearray(b'1.2345')

答案 3 :(得分:0)

新澄清,新答案。我可能会这样做:

import math
SUFFIXES = ['', 'K', 'M']

def convert(s):
    num = s[:len(s) % 3 or 3]
    return '{}{}'.format(num, SUFFIXES[int(math.ceil(len(s) / 3.0) - 1)])

In [1]: from n import convert
In [2]: print convert('123')
123
In [3]: print convert('123123')
123K
In [4]: print convert('12123')
12K
In [5]: print convert('123123123')
123M

您可以通过此答案和其他答案的组合来计算小数。