def f1()
in1="hello"
in2="world"
for i in in1:
for j in in2:
print(ij)
f1()
There two strings in1="hello" in2="world" expected output="hweolrllod"
CodePudding user response:
You can zip
to traverse the two strings together and unpack and join
:
out = ''.join(x for pair in zip(in1, in2) for x in pair)
Output:
'hweolrllod'
CodePudding user response:
A faster version of @enke's answer:
"".join(a1 a2 for a1,a2 in zip(in1, in2))
#'hweolrllod'
CodePudding user response:
Another way could be to use this:-
in1="hello"
in2="world"
print("".join(map("".join, zip(in1, in2))))
CodePudding user response:
You're almost there. Make the below changes in your code:
def f1():
in1="hello"
in2="world"
for i,j in zip(in1, in2):
print(i, j, sep='', end='')
f1()
If you don't want to use zip
, try this:
def f1():
in1="hello"
in2="world"
idx = 0
for i in in1:
for j in in2[idx:]:
print(i, j, sep='', end='')
idx = 1
break
f1()
Output:
hweolrllod
CodePudding user response:
in1 in2
Creates a new, concatenated, string.
But your question seems to indicate you want them only concatenated when printing. For that, do this:
print(in1, in2, sep="")