Python 返回两个字符串中长度相同的交替字母
这里有一个类似的问题,但如果一个单词更长,他们希望返回剩余的字母。我试图为两个字符串返回相同数量的字符 这是我的密码:Python 返回两个字符串中长度相同的交替字母,python,string,Python,String,这里有一个类似的问题,但如果一个单词更长,他们希望返回剩余的字母。我试图为两个字符串返回相同数量的字符 这是我的密码: def one_each(st, dum): total = "" for i in (st, dm): total += i return total x = one_each("bofa", "BOFAAAA") print(x) 它不起作用,但我正在尝试获得所需的输出: >>>bBoOfFaA 我该如何着手解
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_/个(“abcdefghij”,“ABCD”)
时,即当小写字母比大写字母长时,可能会显示错误的结果,但如果您更改输出的每个字母的大小写,则可以很容易地修复此问题。str.join
与zip
连接,因为zip
只成对地迭代到最短的iterable。可以与组合以展平元组的iterable:
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
你是不是在尝试交替组合两个单词?你能给出更多你想要的输出的例子来说明吗?是的,我正试着这么做。例如,如果我有“abcdefghij”和“ABCD”,它应该返回“aAbBcCdD”,您更改大小写是什么意思?对于您的第二次输入,它将返回aAbBcCdD
,这不是您所期望的。因此,您可以交换每个字母的大小写,从而获得输出aAbBcCdD
非常感谢,这很有帮助!