1

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

谢谢。

4

4 回答 4

4
s = "1157903"
s2 = '{}.{}'.format(s[0],s[1:])
于 2013-02-21T04:06:05.887 回答
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
于 2013-02-21T04:22:57.083 回答
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

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

于 2013-02-21T04:35:41.160 回答
0

"1.157903" isn't a decimal, it's a string.

Are you looking to convert a string to a number, or the string representation of a number to a string with a decimal in it?

If it's the former, then:

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

Otherwise:

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

Another method to avoid copying strings is to use a bytearray:

>>> ba = bytearray('12345')
>>> ba.insert(1, ord('.'))
>>> ba
bytearray(b'1.2345')
于 2013-02-21T04:09:56.190 回答