0

I am attempting to format a string in such a way, that I can make a repeating sequence of numbers an arbitrary length.

I've been looking at these examples: How do I format a number with a variable number of digits in Python? and String Formatting in Python 3.

Here's what I tried to do:

print("{0:{1}{2}d}".format(0, 0, 8))

will result in eight pretty 0's all in a row like so: 00000000 but attempting to change the second argument from 0 to 25

print("{0:{1}{2}d}".format(0, 25, 8))

Results in an a single 0 that is as far right as it can go in my console instead of 25252525 So I think the issue is using a string with more than one character as filler instead of a single character.

Community
  • 1
  • 1
Niko
  • 4,158
  • 9
  • 46
  • 85

1 Answers1

1

The specification for string formatting goes like this:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]

In this case, we're only interested in the [0][width] part. [0] is an optional parameter which pads numbers with zeros, so you can format 4 as '004'. [width] specifies the total width of the field.

When you write:

print("{0:{1}{2}d}".format(0, 0, 8))

It becomes:

print("{0:08d}".format(0))

Which is a 0 padded with zeroes up to a length of 8: 00000000.

However, your other example:

print("{0:{1}{2}d}".format(0, 25, 8))

Becomes:

print("{0:258d}".format(0))

Which is a 0 padded with spaces (because there is no 0 in the formatter) up to a length of 258.

I think string formatting is not suited to solve your problem. You can use other fill characters than 0 (using the [fill] option in the formatting spec), but it can't be more than one character.

The simplest way to get what you want is probably this:

>>> print((str(25) * 8)[:8])
25252525
flornquake
  • 3,156
  • 1
  • 21
  • 32