A simplified / faster / more elegant way to split a line at user positions

I was looking for an easier way to do this, but I'm not sure which search options to use. I have a floating point number that I would like to round, convert to a string, and then specify a custom format in the string. I read the .format docs but can't see if it's possible to do this using normal string formatting.

The output I want is a regular line with spaces every three characters, with the exception of the last, which should have a space of four characters to the end.

For example, I made this collapsed function that does what I want is inefficient:

def my_formatter(value):
    final = []
    # round float and convert to list of strings of individual chars
    c = [i for i in '{:.0f}'.format(value)]
    if len(c) > 3:
        final.append(''.join(c[-4:]))
        c = c[:-4]
    else:
        return ''.join(c)
    for i in range(0, len(c) // 3 + 1, 1):
        if len(c) > 2:
            final.insert(0, ''.join(c[-3:]))
            c = c[:-3]
        elif len(c) > 0:
            final.insert(0, ''.join(c))
    return(' '.join(final))

eg.

>>> my_formatter(123456789.12)
>>> '12 345 6789'
>>> my_formatter(12345678912.34)
>>> '1 234 567 8912'

It would be very helpful if you would do it in a simpler and more efficient way.

+4
5

, partition_all. , 3 , 3 . , , .

from toolz.itertoolz import partition_all
def simpleformat(x):
    x = str(round(x))
    a, b = x[:-4], x[-4:]
    strings = [''.join(x[::-1]) for x in reversed(list(partition_all(3, a[::-1])))]
    return ' '.join(strings + [b])
+3

:

def my_formatter(x):
    # round it as text
    txt = "{:.0f}".format(x)

    # find split indices
    splits = [None] + list(range(-4, -len(txt), -3)) + [None]

    # slice and rejoin
    return " ".join(
        reversed([txt[i:j] for i, j in zip(splits[1:], splits[:-1])]))

>>> my_formatter(123456789.1)
12 345 6789
>>> my_formatter(1123456789.1)
112 345 6789
>>> my_formatter(11123456789.1)
1 112 345 6789
+3

, , :

num = 12345678912.34

temp = []
for ix, c in enumerate(reversed(str(round(num)))):
    if ix%3 == 0 and ix !=0: temp.extend([c, ' '])
    else: temp.extend(c)

''.join(list(reversed(temp)))

:

'1 234 567 8912'

,

num = 12345678912.34

''.join(list(reversed(list(''.join([c+' ' if(ix%3 == 0 and ix!=0) else c for ix, c in enumerate(reversed(str(round(num))))])))))

'1 234 567 8912'

+2

- , , .

import locale

for v in ('fr_FR.UTF-8', 'en_GB.UTF-8'):
    locale.setlocale(locale.LC_NUMERIC, v)
    print(v, '>> {:n}'.format(111222333999))
+2

, , - , . , , python , - . , , , , , VB format ( , "### #### 0" ). , , , Python.format.

, . , , , .

def format_number(num, pat, sep=' '):
    fmt = []
    strn = "{:.0f}".format(num)
    while strn:
        p = pat.pop() if pat else p
        fmt.append(strn[-p:])
        strn = strn[:-p] if len(strn) > p else ''
    return sep.join(fmt[::-1])

>>> format_number(123456789, [3, 4])
>>> '12 345 6789'
>>> format_number(1234567890, [3])
>>> '1 234 567 890'
+1

Source: https://habr.com/ru/post/1694843/


All Articles