5

Can you please explain if I need to pass the variable multiple times for the string concatenation.

For eg.

String1 = "Hello"
String = "Good Morning"    
String2 = String + "%s, %s" % (String1, String1)

My question is, how do I pass String1 just once?

Is there a better way to do it?

3
  • If your intended output is "HelloHelloHello" then yes Commented Dec 17, 2014 at 19:13
  • Where is the variable String defined? Commented Dec 17, 2014 at 19:13
  • @Kevin - Sorry I missed that. Commented Dec 17, 2014 at 19:15

1 Answer 1

6

If you use the newer str.format method, you can do:

String2 = String + "{0}, {0}".format(String1)

In fact, you should always prefer str.format over % formatting in modern Python. The latter approach is pseudo-deprecated and will most likely be removed from a future version of the language.

Sign up to request clarification or add additional context in comments.

2 Comments

The best solution would be: String2 = "{0}{1}, {1}".format(String, String1)
I was trying earlier to accept your answer but for some reasons, SO was not letting me. Now I could do it.

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.