簡體   English   中英

從兩個字符串返回具有相同長度的交替字母

[英]Return Alternating Letters With the Same Length From two Strings

這里也有類似的問題,但是如果一個單詞更長,他們希望剩下的字母返回。 我正在嘗試為兩個字符串返回相同數量的字符。

這是我的代碼:

def one_each(st, dum):
    total = ""

    for i in (st, dm):
        total += i
    return total
x = one_each("bofa", "BOFAAAA")
print(x)

它不起作用,但我正在嘗試獲得所需的輸出:

>>>bBoOfFaA

我將如何解決這個問題? 謝謝!

我可能會做這樣的事情

s1 = "abc"
s2 = "123"
ret = "".join(a+b for a,b in zip(s1, s2))
print (ret)

這是一個簡短的方法。

def one_each(short, long):
    if len(short) > len(long):
        short, long = long, short # Swap if the input is in incorrect order

    index = 0
    new_string = ""
    for character in short:
        new_string += character + long[index]
        index += 1

    return new_string            

x = one_each("bofa", "BOFAAAA") # returns bBoOfFaA
print(x)

當您輸入x = one_each("abcdefghij", "ABCD")時,即當小寫字母長於大寫字母時,它可能會顯示錯誤的結果,但是如果您更改輸出中每個字母的case ,則很容易解決。

str.joinzip str.join使用,因為zip僅成對進行迭代,直到最短的迭代為止。 您可以將它與itertools.chain結合使用以使可迭代的元組變平:

from itertools import chain

def one_each(st, dum):
    return ''.join(chain.from_iterable(zip(st, dum)))

x = one_each("bofa", "BOFAAAA")

print(x)

bBoOfFaA

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM