Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7 format string padding with more than one char

The Problem

I've been able to pad a string with asterisk, however I'd like to see if it is possible to pad it with an asterisk and a space.

Example Output

What I've been able to get

****************************Hello World***************************

... trying to get

* * * * * * * * * * * * * * Hello World* * * * * * * * * * * * * *

Attempts

Naively I tried passing a " *" to the fill parameter of the format specs. This returned with an error:

Traceback (most recent call last): File "main.py", line 17, in <module> ret_string = '*{:{f}^{n}}'.format(string, f=filler, n=line_len) ValueError: Invalid conversion specification

Then I tried using an escape character, "\s*", which yielded the same result. Finally I revisited the documentation 6.1.3.1. Format Specification Mini-Language and see the input spec appears to be limited to a character and not open to strings. Is there a way around this? I thought of making a sort of compound reference ie {{char1}{char2}} but that doesn't seemed to have worked either.

Thoughts?

The Code

import fileinput

string     = "Hello World"
ret_string = ""
line_len   = 65
filler    = " *"


for inputstring in fileinput.input():
    string = inputstring.strip(" \n")

ret_string = '{:{f}^{n}}'.format(string, f=filler, n=line_len)
print(ret_string)
like image 523
TekkSparrow Avatar asked Sep 13 '26 14:09

TekkSparrow


1 Answers

The following would work for two character fill patterns:

string = "Hello World"
length = 65
fill = "* "

output = string.center(length, '\x01').replace('\x01\x01', fill).replace('\x01', fill[0])
print(len(output), output)

Python has a center() function which will pad a string with a single character pad character. You could then replace runs of 2 with your fill pattern. This could result in a single character, thus a second replace is used for this eventuality. It uses the character \x01 as a character unlikely to be in string.

The length of output is printed to prove it is the correct length.

65 * * * * * * * * * * * * * *Hello World* * * * * * * * * * * * * *
like image 157
Martin Evans Avatar answered Sep 15 '26 02:09

Martin Evans