'How to concatenate two strings in python? [duplicate]
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"
Solution 1:[1]
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
Solution 2:[2]
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'
Solution 3:[3]
Another way could be to use this:-
in1="hello"
in2="world"
print("".join(map("".join, zip(in1, in2))))
Solution 4:[4]
A faster version of @NewbieAF's answer:
"".join(a1+a2 for a1,a2 in zip(in1, in2))
#'hweolrllod'
Solution 5:[5]
This isn't the most efficient way but is easier to understand in terms of the logic needed.
def f1() -> None:
in1 = "hello"
in2 = "world"
i = 0
j = 0
op = ""
while i<len(in1) and j<len(in2):
op = op + in1[i]
op = op + in2[j]
i = i + 1
j = j + 1
print(op)
f1()
Output
hweolrllod
Since you haven't mentioned the case where strings have different lengths, I have left that part.
Solution 6:[6]
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="")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | AlveMonke |
| Solution 4 | |
| Solution 5 | Rinkesh P |
| Solution 6 | Keith |
