连接两个字符串元素明智

发布于 2025-01-28 09:33:31 字数 395 浏览 6 评论 0原文

我遇到了一个问题,我不得不加入两个字符串元素明智 对于ex:

str1 = "ABCD"
str2 = "EFGH"
output = "AEBFCGDH"

我写了此代码

op = ''
op = op.join([i + j for i, j in zip(str1, str2)])
print(op)

,它奏效了,但我想知道两个字符串的长度是否不同 对于Ex:

str1 = "ABC"
str2 = "DEFGH"
output = "ADBECFGH"

or

str1 = "ABCDG"
str2 = "DEF"
output = "ADBECFDG"

如何为此编码?

I came across a problem in which i had to concatenate two string element wise
for ex :

str1 = "ABCD"
str2 = "EFGH"
output = "AEBFCGDH"

I wrote this code

op = ''
op = op.join([i + j for i, j in zip(str1, str2)])
print(op)

And it worked but I was wondering if the length of two strings is different
for ex:

str1 = "ABC"
str2 = "DEFGH"
output = "ADBECFGH"

or

str1 = "ABCDG"
str2 = "DEF"
output = "ADBECFDG"

How do I code for this ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

萌能量女王 2025-02-04 09:33:31

只需切换zip()带有zip_longest()

from itertools import zip_longest
str1 = "ABCDG"
str2 = "DEF"
output = ''.join([i + j for i, j in zip_longest(str1, str2, fillvalue="")])
print(output)  # ADBECFDG

Just switch zip() with zip_longest():

from itertools import zip_longest
str1 = "ABCDG"
str2 = "DEF"
output = ''.join([i + j for i, j in zip_longest(str1, str2, fillvalue="")])
print(output)  # ADBECFDG
懒猫 2025-02-04 09:33:31

您可以取较短的字符串,拉链直至其长度,然后将较长字符串的其余部分串联。
例如:

str1 = 'ABC'
str2 = 'DEFGH'
op = ''
if len(str1)>len(str2):
    op = op.join([i + j for i, j in zip(str1, str2)])+str1[len(str2):]
else:
    op = op.join([i + j for i, j in zip(str1, str2)]) + str2[len(str1):]
print(op) # output: ADBECFGH

Zip()仅拉链,直到两个迭代的较短。
请参阅: https://docs.pypython.org/3.3/library/functions。 html#zip

You could take the shorter string, zip until its length and then concatenate the remaining part of the longer string.
eg:

str1 = 'ABC'
str2 = 'DEFGH'
op = ''
if len(str1)>len(str2):
    op = op.join([i + j for i, j in zip(str1, str2)])+str1[len(str2):]
else:
    op = op.join([i + j for i, j in zip(str1, str2)]) + str2[len(str1):]
print(op) # output: ADBECFGH

zip() only zips until the shorter of the two iterables.
See: https://docs.python.org/3.3/library/functions.html#zip

回心转意 2025-02-04 09:33:31

简单解决方案:

str1 = "ABCDG"
str2 = "DEF"
suffix_start = min(len(str1), len(str2))
suffix = str1[suffix_start:]+str2[suffix_start:]
output = ''.join([i + j for i, j in zip(str1, str2)]) + suffix
print(output)  # ADBECFDG

Simple solution:

str1 = "ABCDG"
str2 = "DEF"
suffix_start = min(len(str1), len(str2))
suffix = str1[suffix_start:]+str2[suffix_start:]
output = ''.join([i + j for i, j in zip(str1, str2)]) + suffix
print(output)  # ADBECFDG
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文