Hello is there a function that will get a string S and a number n and will add (n-1) # at the start and (n-1) % at the end. In python. I know how to add a char but not a number of them. Example S= abracatabra and n =3 result : ##abracatabra%%
2 Answers
I think this does what you want:
string = "test"
n = 3
for i in range(1,n):
string = "#"+string+"%"
print(string)
The version of @idjaw is better optimized that this solution but remember you can just add strings using +.
Alternative version:
string = "#"*(n-1)+string+"%"*(n-1)
This can also be achieved using Python's Format Specification Mini-Language specification. This allows pad characters and widths to be specified as follows:
n = 5
text = "abracatabra"
print "{:#>{w}}{}{:%>{w}}".format("", text, "", w=n-1)
This would display:
####abracatabra%%%%
In effect this is printing 3 items, firstly an empty string padded with n-1 # fill characters. Secondly the text string. Lastly another empty string padded with n-1 % fill characters.
new_str = "{}{}{}".format((n - 1) * '#', S, (n - 1) * '%')