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

时间:2023-01-08 16:02:10

I have two strings, (string1 and string2).

我有两个字符串(string1和string2)

If they are equal in length, the function should return a string that is formed by alternating characters from each of the two strings.

如果它们的长度相等,函数应该返回一个字符串,该字符串是由两个字符串中的每个字符交替组成的。

If they are not equal in length, then the function extends the shorter string by repeating the last character until they are the same length and then alternates the characters of the two strings.

如果它们的长度不相等,那么函数通过重复最后一个字符来扩展较短的字符串,直到它们的长度相等,然后替换两个字符串的字符。

For example,

例如,

extendedString("abc", "def") =>  "adbecf" 
extendedString("ab", "defg") =>  "adbebfbg"

I have written the part where it returns if the strings are the same length, but I have no idea how to repeat the last character.

如果字符串长度相同,我已经编写了它返回的部分,但是我不知道如何重复最后一个字符。

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 个解决方案

#1


11  

You can use the zip_longest function from itertools.
Works like zip, but gives you the ability to fill the blanks (default filler is None, but you can change it:

您可以使用来自itertools的zip_long函数。可以像zip一样工作,但是可以填充空格(默认填充是None,但是可以修改:

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)

update

added the filler to be the last char of the shortest string (in case it's needed)

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

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

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

If you are using python2 the function is itertools.izip_longest

如果您正在使用python2,函数是itertools.izip_longest

#2


7  

A one-liner solution that doesn't require 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))))

Output:

输出:

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

#3


2  

First make both the strings of same length and then join. Something like:

首先使两个字符串的长度相同,然后连接。喜欢的东西:

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") 

Output:

输出:

$ python test.py
adbecf
adbebfbg
daebfbgb
$

#4


2  

Simply add the last character to the shorter string until their length is same. In python, string*int is defined. For example "a"*3 is "aaa". So x = x+x[-1]*(len(y)-len(x)) does what you need to do. Then you just need to recursively call the function with the new string values that have the same length.

只需将最后一个字符添加到较短的字符串中,直到它们的长度相同。在python中,定义了字符串*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)

#5


1  

You can accomplish the case where the length is not equal by finding the shorter and the longer of the strings, and appending N of the -1th character of the shorter string to itself, where N is the difference in length between the shorter and longer. From there, you return the same zip/join expression.

如果长度不相等,你可以通过查找字符串的短和长来完成,并将短字符串的-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)

#6


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

#7


1  

OK, I realize this has been answered into oblivion, but I had already started working on mine, so here it goes.

好吧,我知道这个答案已经被遗忘了,但我已经开始研究我的了,所以就这样。

Note: this implementation will always start printing the shorter string first, if you want to always start off by printing the first char of string1, then see my update below.

注意:此实现将始终首先开始打印较短的字符串,如果您希望始终从打印string1的第一个字符开始,那么请参阅下面的更新。

I like that you copy the input parameters as that is a good habit for preserving input, and I just modified it slightly to add a convention so len(x) <= len(y) is always true. I also opted to not use other libraries but to implement the zip myself.

我喜欢你复制输入参数,因为这是一个保存输入的好习惯,我只是稍微修改一下,添加一个约定,这样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"))

Output:

输出:

$ python zip.py
aebfcg
adbebfbg
eafbfcfd

Update

This implementation will ensure that string1 is always printed first.

此实现将确保始终先打印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"))

Output:

输出:

$ python zip.py
aebfcg
adbebfbg
aebfcfdf

#1


11  

You can use the zip_longest function from itertools.
Works like zip, but gives you the ability to fill the blanks (default filler is None, but you can change it:

您可以使用来自itertools的zip_long函数。可以像zip一样工作,但是可以填充空格(默认填充是None,但是可以修改:

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)

update

added the filler to be the last char of the shortest string (in case it's needed)

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

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

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

If you are using python2 the function is itertools.izip_longest

如果您正在使用python2,函数是itertools.izip_longest

#2


7  

A one-liner solution that doesn't require 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))))

Output:

输出:

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

#3


2  

First make both the strings of same length and then join. Something like:

首先使两个字符串的长度相同,然后连接。喜欢的东西:

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") 

Output:

输出:

$ python test.py
adbecf
adbebfbg
daebfbgb
$

#4


2  

Simply add the last character to the shorter string until their length is same. In python, string*int is defined. For example "a"*3 is "aaa". So x = x+x[-1]*(len(y)-len(x)) does what you need to do. Then you just need to recursively call the function with the new string values that have the same length.

只需将最后一个字符添加到较短的字符串中,直到它们的长度相同。在python中,定义了字符串*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)

#5


1  

You can accomplish the case where the length is not equal by finding the shorter and the longer of the strings, and appending N of the -1th character of the shorter string to itself, where N is the difference in length between the shorter and longer. From there, you return the same zip/join expression.

如果长度不相等,你可以通过查找字符串的短和长来完成,并将短字符串的-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)

#6


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

#7


1  

OK, I realize this has been answered into oblivion, but I had already started working on mine, so here it goes.

好吧,我知道这个答案已经被遗忘了,但我已经开始研究我的了,所以就这样。

Note: this implementation will always start printing the shorter string first, if you want to always start off by printing the first char of string1, then see my update below.

注意:此实现将始终首先开始打印较短的字符串,如果您希望始终从打印string1的第一个字符开始,那么请参阅下面的更新。

I like that you copy the input parameters as that is a good habit for preserving input, and I just modified it slightly to add a convention so len(x) <= len(y) is always true. I also opted to not use other libraries but to implement the zip myself.

我喜欢你复制输入参数,因为这是一个保存输入的好习惯,我只是稍微修改一下,添加一个约定,这样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"))

Output:

输出:

$ python zip.py
aebfcg
adbebfbg
eafbfcfd

Update

This implementation will ensure that string1 is always printed first.

此实现将确保始终先打印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"))

Output:

输出:

$ python zip.py
aebfcg
adbebfbg
aebfcfdf