[英]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.join
與zip
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.