-2

I have a string:

testString = """ My name is %s
and I am %s years old
and I live in %s"""

I have code that finds these three strings that I want to input into testString. How do I do that? In Java I would've done:

return String.format(testString, string1, string2, string3)

Is there an equivalent in Python?

hokosha
  • 305
  • 2
  • 4
  • 11
  • 2
    I searched for "Python string formatting" and "Python formatted string" on Google. In both cases the relevant documentation was the first hit. Did you find that documentation? Did you run into problems with implementing that? – Martijn Pieters Aug 04 '15 at 10:43
  • http://stackoverflow.com/questions/5082452/python-string-formatting-vs-format – Padraic Cunningham Aug 04 '15 at 10:44
  • @MartijnPieters Yes, I did, but ran into problems. It is fixed now though, thanks to the answer given. – hokosha Aug 04 '15 at 10:50
  • @hokosha: then *share that information*. Always share your research. If you ran into a problem we can help you fix that problem. – Martijn Pieters Aug 04 '15 at 10:51
  • @MartijnPieters Alright, I understand. The thing was that I needed to return that string, like I did in my Java example. I realize that I did not really clarify that, though. – hokosha Aug 04 '15 at 11:00

1 Answers1

7

this is the version using %:

print """ My name is %s
and I am %s years old
and I live in %s""" % ('tim', 6, 'new york')

and this my preferred version:

testString = """ My name is {}
and I am {} years old
and I live in {}""".format(string1, string2, string3)

you may want to read https://docs.python.org/3.4/library/string.html#string-formatting .

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111