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
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
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
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.
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
There is a simple answer:
print("Hello %s, how are %s, %s" % ("world", "you", 1))
Output:
Hello world, how are you, 1