1

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%%

1
  • 2
    new_str = "{}{}{}".format((n - 1) * '#', S, (n - 1) * '%') Commented Mar 12, 2017 at 16:52

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Not quite, no. It's supposed to be (n - 1). Your final result will end up having three '#' and three '%'
@idjaw thnx for letting me know. fixed it.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.