Python - format integer with dot on the end

Viewed 2671

How to create this kind of strings with python:

" 2558.     "
" 2.        "
" 1224456.  "

I have integer, 11 spaces and .. First is leading space, then integer, after integer is dot, and after dot are spaces untill it reaches 11 places

I can go:

x = "{: d}{}".format(25, '.')
y = "|{:11s}|".format(x)

print:

| 25.       |

Is it possible to do that in one line and one string?

7 Answers

All of the existing answers that suggest using arithmetic to calculate the argument to ljust technically work, but they seem unnecessarily complicated to me... It seems like it would be easier to compose the rest of the string first, and call ljust on the result, no arithmetic required.

for x in [2558, 2, 1224456, 25]:
    s = f" {x}.".ljust(11)
    print("\ninput:", x)
    print("output (no pipe):", s)
    print("output (with pipe):", "|" + s + "|")

Result:

input: 2558
output (no pipe):  2558.
output (with pipe): | 2558.     |

input: 2
output (no pipe):  2.
output (with pipe): | 2.        |

input: 1224456
output (no pipe):  1224456.
output (with pipe): | 1224456.  |

input: 25
output (no pipe):  25.
output (with pipe): | 25.       |

String addition plus .ljust() method will do the trick:

>>> x = 25
>>> x = ' '+str(x)+'.'.ljust(11-(len(str(x)+'.')))
>>> x
' 25.       '

The string format works quite well if you want a concise solution.

Since you want a total of 11 chars, including the leading space and the period, the ljust will require 10 minus the length of the integer.

for i in [2558, 2, 1224456]:
    print(f" {i}{'.'.ljust(10-len(str(i)))}")

' 2558.     '
' 2.        '
' 1224456.  '

The single quotation above is just to indicate the start and end of the string.

Use ljust on the result of the format method (which is just https://stackoverflow.com/a/58433145/1126841 using the format method instead of f-strings):

>>> ' {}.'.format(1224456).ljust(11)
' 1224456.  '
>>> ' {}.'.format(2558).ljust(11)
' 2558.     '
>>> ' {}.'.format(2).ljust(11)
' 2.        '
>>> ' {}.'.format(1224456).ljust(11)
' 1224456.  '

You can use the format() method in combination with the f-string:

for i in [2558, 2, 1224456, 25]:
    print('"{:<11}"'.format(f'{i}.'))

Output:

"2558.      "
"2.         "
"1224456.   "
"25.        "

Like this ?

integer = 25

x = f"| {integer}." + " "*11 + "|"

print(x)

output :

| 25.           |

EDIT

integer = 25
x = f"| {integer}."+" "*(11-(len(str(integer))+2))+"|"

print(x)

output :

| 25.       |
x = 2545
x = str(x)+'.'
x = ' '+x.ljust(11-len(x))
print x
Related