Eg: I have a list
temp = ["TOM", "JOHN"]
I want to join such that the result is
" Hi! TOM Welcome. Hi! JOHN Welcome."
Something whose pseudocode would be like this
"Hi! {} Welcome.".join(temp)
CodePudding user response:
Sure. A combination of a generator expression (or a list comprehension) and a " ".join
to join the formatted texts.
>>> names = ["TOM", "JOHN"]
>>> " ".join(f"Hi! {name} welcome." for name in names)
'Hi! TOM welcome. Hi! JOHN welcome.'
CodePudding user response:
There are many possibilities for string formatting, here is one using f-strings:
l = ["TOM", "JOHN"]
' '.join(f'Hi {i}! Welcome.' for i in l)
output:
'Hi TOM! Welcome. Hi JOHN! Welcome.'
Here is another, using format
:
l = ["TOM", "JOHN"]
' '.join('Hi {0}! Welcome.'.format(i) for i in l)
And finally, the good old %
substitution:
l = ["TOM", "JOHN"]
' '.join('Hi %s! Welcome.' % i for i in l)
CodePudding user response:
You can use a so called f-string. In addition to that I used a function that lets you change the message easily:
temp = ["TOM", "JOHN"]
def message(name):
return f"Hi! {name} Welcome."
out = " ".join(message(i) for i in temp)
print(out)