我很难尝试将此 Javascript 代码移植到 Python。在 Javascript 中,该函数可以采用两个字符串,例如 str1=123456 和 str2=passwo。然后它会输出类似 p1a2s3s4w5o6 的东西
在 python 中,它只是将它结合起来。如果可能的话,请有人告诉我如何使用 python 中的 if 语句来完成。也许我需要以另一种方式来做。谢谢你的帮助。
Python 示例
def merge(str1, str2):
arr1 = str1.split();
arr2 = str2.split();
result = "";
index1 = 0;
index2 = 0;
while ((index1 < len(arr1)) or (index2 < len(arr2))):
if(index1 < len(arr1)):
result += arr1[index1];
print("part1")
index1 = index1+1;
if(index2 < len(arr2)):
result += arr2[index2];
index2 = index2+1;
print(result);
return result;
Run Code Online (Sandbox Code Playgroud)
Javascript 示例
function merge(str1, str2){
var arr1 = str1.split("");
var arr2 = str2.split("");
var result = "";
var index1 = 0;
var index2 = 0;
while((index1 < arr1.length) || (index2 < arr2.length)){
if(index1 < arr1.length){
result += arr1[index1];
index1++;
}
if(index2 < arr2.length){
result += arr2[index2];
index2++;
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
用:
def merge(str1, str2):
return "".join(x + y for x, y in zip(str(str1), str(str2)))
print(merge("passwo", 123456))
Run Code Online (Sandbox Code Playgroud)
这打印:
p1a2s3s4w5o6
Run Code Online (Sandbox Code Playgroud)