Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

python - 如何将2个字符串压缩为python中的新字符串[重复](How to zip 2 strings into a new string in python [duplicate])

I am try to figure out how to zip two strings of different length into one string alternating the chars and preserving the leftover chars in the longer string.

(我试图弄清楚如何将两个不同长度的字符串压缩为一个字符串,以交替字符和在剩余的字符串中保留剩余的字符。)

Example:

(例:)

a = '12345'
b = 'abcdefgh'

I tried zip(a,b) but it returns a list of tuples and cuts off when there aren't equal length strings:

(我试过zip(a,b)但是它返回一个元组列表,并在长度不相等的字符串时切断:)

[('1', 'a'), ('2', 'b'), ('3', 'c'), ('4', 'd'), ('5', 'e')]

I need to get just the new string out.

(我只需要取出新字符串。)

Example:

(例:)

result = 1a2b3c4d5efgh

How can this be done?

(如何才能做到这一点?)

  ask by smitty translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One possible way: join the inner tuples and then the outer list.

(一种可能的方式:加入内部元组,然后加入外部列表。)

''.join(''.join(x) for x in zip(a,b))

Though, zip() will always stop aggregating when the shortest beween a and b ends ( 1a2b3c4d5e in your example).

(不过,当ab之间的最短端点(在您的示例中为1a2b3c4d5e )结束时, zip()将始终停止聚合。)

If you want to reach the end of the longest input string you must iterate them differently, for example:

(如果要到达最长输入字符串的末尾,则必须进行不同的迭代,例如:)

c = [] 
for x in range(max(len(a),len(b))):
    c.append(a[x] if x < len(a) else '')
    c.append(b[x] if x < len(b) else '')
result=''.join(c)

Or, as suggested by Moinuddin below, using izip_longest :

(或者,如下面的izip_longest建议的那样,使用izip_longest :)

''.join(''.join(x) for x in izip_longest(a, b, fillvalue=''))

NOTE that as of Python 3, izip_longest() is now zip_longest() .

(注意 ,从Python 3开始, izip_longest()现在为zip_longest() 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...