-4

I have a string such as: "Hello %s, how are %s, %s"

I need to replace all occurrences of %s with the elements of the tuple ("world", "you", 1) in order for the output to be:

Hello world, how are you, 1
solid.py
  • 2,782
  • 5
  • 23
  • 30
Gaurav Sharma
  • 349
  • 4
  • 13
  • 2
    `"Hello %s, how are %s, %s" % ("world", "you", 1)`? See e.g. https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting. – jonrsharpe Sep 07 '20 at 09:51
  • Does this answer your question? [How to print like printf in Python3?](https://stackoverflow.com/questions/19457227/how-to-print-like-printf-in-python3) – funie200 Sep 07 '20 at 09:53
  • Hey @Gaurav Sharma would you like to replace string occurences or merely print using format()? – solid.py Sep 07 '20 at 09:56
  • Does this answer your question? [String formatting: % vs. .format vs. string literal](https://stackoverflow.com/questions/5082452/string-formatting-vs-format-vs-string-literal) – Zoe Sep 07 '20 at 11:32

4 Answers4

2

You can use the .format() method:

print("Hello {0}, how are {1}, {2}".format(*("world", "you", 1)))

The star * allows you to unpack the tuple so the .format() function can elaborate them.

Look here for more examples.

In case you don't want to use the .format(), take a look at this:

print("Hello %s, how are %s, %s" % (("world", "you", 1)))

Both method will output:

Hello world, how are you, 1
Carlo Zanocco
  • 1,967
  • 4
  • 18
  • 31
2

You could do something like this:

def tupleFormat(string, format):
    return string % format

and then you could do yout example like:

tupleFormat("Hello %s, how are %s, %s", ("world", "you", 1))

You can use the % operator on strings and tuples, exactly how you want it.

solid.py
  • 2,782
  • 5
  • 23
  • 30
Luke_
  • 745
  • 10
  • 23
1

If your aim is to replace string occurrences, you could try the following:

string = 'Hello %s, how are %s, %s'
tupl = ('world', 'you', '1')

for t in tupl:
  string = string.replace('%s', t, 1)

print(string)

Output:

Hello world, how are you, 1
solid.py
  • 2,782
  • 5
  • 23
  • 30
1

There is a simple answer:

print("Hello %s, how are %s, %s" % ("world", "you", 1))

Output:

Hello world, how are you, 1
aalmeida
  • 19
  • 1