合并两个字符串(逐个字符合并),并重复最短字符串的最后一个字符

9
我有两个字符串(string1和string2)。
如果它们的长度相等,函数应该返回一个由两个字符串中的字符交替组成的字符串。
如果它们的长度不相等,则函数会将较短的字符串重复最后一个字符直到它们长度相同,然后交替两个字符串中的字符。
例如,
extendedString("abc", "def") =>  "adbecf" 
extendedString("ab", "defg") =>  "adbebfbg"

我已经编写了检查字符串是否长度相等的代码,但我不知道如何重复最后一个字符。

def extendedString(string1, string2):
    x = string1
    y = string2
    z = ""
    if len(x) == len(y):
        return "".join(i for j in zip(string1,string2) for i in j)
7个回答

11
您可以使用itertools中的zip_longest函数,它类似于zip,但能够填充空白(默认为None,但您可以更改填充值)。:zip_longest 函数
import itertools

def extendedString(string1,string2):
    filler = string2[-1] if len(string1)>len(string2) else string1[-1]
    return "".join(i for j in itertools.zip_longest(string1, string2, fillvalue=filler) for i in j)

更新

将填充字符添加为最短字符串的最后一个字符(如果需要的话)

In [50]: extendedString("abc","def")
Out[50]: 'adbecf'

In [51]: extendedString("ab","defg")
Out[51]: 'adbebfbg'

如果您使用的是 Python2,则函数名为 itertools.izip_longest


哦,不错。我不知道那个。 - Jordan McQueen
3
itertools 是一个非常好的库 :) 可以帮助你节省大量时间(和代码!) - Dekel
感谢您的点赞,如果您能告诉我为什么给我点了踩,我将不胜感激。谢谢! - Dekel

7

一种不需要 itertools一行代码 解决方案:

def extendedString(a,b):
    return ''.join(x+y for x,y in zip(*(s+s[-1]*(max(len(a),len(b))-len(s)) for s in (a,b))))

输出:

$ extendedString('abc','1234')
'a1b2c3c4'
$ extendedString('abc','12')
'a1b2c2'

2

只需将最后一个字符添加到较短的字符串中,直到它们的长度相同。在Python中,定义了string*int。例如,"a"*3"aaa"。所以x = x+x[-1]*(len(y)-len(x))就是你需要做的。然后,您只需要使用具有相同长度的新字符串值递归调用函数即可。

def extendedString(string1,string2):
    x=string1
    y=string2
    z=""
    if len(x)==len(y):
        return "".join(i for j in zip(string1,string2) for i in j)
    elif len(x) < len(y):
        x = x+x[-1]*(len(y)-len(x))
        return extendedString(x,y)
    else:
        y = y+y[-1]*(len(x)-len(y))
        return extendedString(x,y)

2

首先将两个字符串变成相同的长度,然后再拼接起来。可以像这样:

def extendedString(string1,string2):
    x=string1
    y=string2

    if len(x) < len(y):
        x = x + x[-1] * (len(y) - len(x))
    elif len(x) > len(y):
        y = y + y[-1] * (len(x) - len(y))

    return "".join(i for j in zip(x, y) for i in j)

print extendedString("abc", "def")
print extendedString("ab","defg") 
print extendedString("defg","ab") 

输出:

$ python test.py
adbecf
adbebfbg
daebfbgb
$

1
你可以通过找到两个字符串中的短字符串和长字符串,并将短字符串的第-1个字符附加N次到它本身上,其中N是短字符串和长字符串之间的长度差异,来实现长度不相等的情况。然后,您返回相同的zip/join表达式。
def extendedString(string1, string2):
    if len(string1) == len(string2):
        return "".join(i for j in zip(string1, string2) for i in j)
    else:
        longer, shorter = (string1, string2) if len(string1) > len(string2) else (string2, string1)
        shorter = shorter + shorter[-1] * (len(longer) - len(shorter))
        return "".join(i for j in zip(shorter, longer) for i in j)

1
a = "hell"
b = "heaven"
print "".join(i for j in itertools.izip_longest(a, b, fillvalue=a[-1] if len(a)<len(b) else b[-1]) for i in j)

Output: hheelalvleln

1

好的,我知道这个问题已经被解答得面目全非了,但是我已经开始着手解决我的问题,所以让我们开始吧。

注意:这种实现方式总是先打印较短的字符串,如果您想始终从打印string1的第一个字符开始,请参见下面的我的更新。

我喜欢你复制输入参数,因为这是保留输入的好习惯,我只稍微修改了一下,添加了一个约定,使得 len(x) <= len(y) 总是成立。我也选择不使用其他库,而是自己实现了zip函数。

def extendedString(string1, string2):
    if len(string1) <= len(string2):  # Convention: len(x) <= len(y)
        x = string1
        y = string2
    else:
        x = string2
        y = string1
    z=""
    for i in range(len(x)):           # Go through shorter string
        z+=x[i]                       # Add the i-th char in x to z
        z+=y[i]                       # Add the i-th char in y to z
    if i < len(y):                    # If the second string is longer
        for j in range(i+1, len(y)):  # for the rest of the length
            z+=x[i]                   # add the last char of x to z
            z+=y[j]                   # add the j-th char of y to z
    return z

print(extendedString("abc", "efg"))
print(extendedString("ab", "defg"))
print(extendedString("abcd", "ef"))

输出:

$ python zip.py
aebfcg
adbebfbg
eafbfcfd

更新

这个实现将确保string1总是先被打印。

def extendedString(string1, string2):
    x = string1
    y = string2
    z=""
    if len(x) <= len(y):
        shorter = x
        longer = y
    else:
        shorter = y
        longer = x
    for i in range(len(shorter)):
        z+=x[i]
        z+=y[i]
    if i < len(longer):
        for j in range(i+1, len(longer)):
            if shorter == x:
                z+=x[i]
                z+=y[j]
            else:
                z+=x[j]
                z+=y[i]
    return z

print(extendedString("abc", "efg"))
print(extendedString("ab", "defg"))
print(extendedString("abcd", "ef"))

输出:

$ python zip.py
aebfcg
adbebfbg
aebfcfdf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接