Anders
Anders

Reputation: 17554

Format int as 000000_0000

In ironpython (Python 2.7) can I format an int to output a string like this:

1     --> 000000_0001
10000 --> 000001_0000

The "{}".format syntax doesn't seem to support custom chars.

This is what I tried for now:

def format(self, num):
    pre = int(num * 0.0001)
    tail = int(num - (pre*1/0.0001))

    return "{}_{}".format("{0:06d}".format(pre), "{0:04d}".format(tail))

But I was hoping there was a cleaner way. In C# it would have been:

num.ToString("000000_0000")

edit: I ended up with a variant of Parsa

def format(num):
    num = str(num).zfill(10)
    return "{}_{}".format(num[0:6], num[6:10])

Upvotes: 1

Views: 209

Answers (3)

Mustafa Aydın
Mustafa Aydın

Reputation: 18296

What about:

total_length = 8
half_length = total_length / 2

num = 10000

zfilled_num = str(num).zfill(total_length)
underscored = zfilled_num[:half_length] + "_" + zfilled_num[half_length:]

print underscored
# 0001_0000

Try it online!

Upvotes: 2

baduker
baduker

Reputation: 20042

As @Karl suggested create a padded string first and then insert the _.

Here's how:

def halve_it(n):
    p = '{:010d}'.format(n)
    return '{}_{}'.format(p[:6], p[6:])

print halve_it(12345)

Output:

>>> def halve_it(n):
...     p = '{:010d}'.format(n)
...     return '{}_{}'.format(p[:6], p[6:])
...
>>> print halve_it(10000)
000001_0000
>>> >>> print halve_it(12345)
000001_2345
>>> print halve_it(1)
000000_0001
>>> print halve_it(9876543)
000987_6543

Upvotes: 1

Parsa Hz
Parsa Hz

Reputation: 61

def print_with_format(i):
    print("{0}_{1}".format(str(i).zfill(8)[0:4], str(i).zfill(8)[4:8]))

print_with_format(18965)

enter image description here

Upvotes: 2

Related Questions