给你两个字符串 word1 和 word2 。请你从 word1 开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。返回合并后的字符串
一行代码解决
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
return ''.join(a + b for a, b in zip_longest(word1, word2, fillvalue=''))
''.join() 表示 将一个空的字符串作为连接符,将序列中的每个字符串连接起来,生成一个新的字符串。示例如下:
a = ['hello', 'world', '!']
b = ''.join(a)
print(b)
输出结果为:
helloworld!
zip_longest() 是itertools的一个函数,是zip() 函数的升级版。可以将多个不同长度的列表一一对应。如果列表a和b的长度不一样,就会在缺少元素的位置使用默认填充值None。
fillvalue=' ' fillvalue是zip_longest函数的一个参数,是用于填充缺失位置的值。
fillvalue的默认值为None,如果不提供其他值,那么在缺失位置
[Something went wrong, please try again later.]
示例如下:
from itertools import zip_longest
a = [1, 2, 3]
b = ['a', 'b']
for item in zip_longest(a, b, fillvalue=0):
print(item)
输出结果为:
(1, 'a')
(2, 'b')
(3, 0)