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.
What I've been able to get
****************************Hello World***************************
... trying to get
* * * * * * * * * * * * * * Hello World* * * * * * * * * * * * * *
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?
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)
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* * * * * * * * * * * * * *
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With