在python中使用for循环将两个字符串转换为一个字符串

时间:2014-03-25 01:07:16

标签: python

例如:

  

轧液机( '你好', '人') - > 'hpeelolpole'

这意味着要逐个字符地组合这两个字符串。 这是我的功能:

def mangle(s1,s2):
  s1=list(s1)
  s2=list(s2)
  a=" "
  for i in range(0,min(len(s1),len(s2))):        
    for c in s1:
      for d in s2:
        a=a+c+d
        if len(s1)>len(s2):
          return a+''.join(s1)[min(len(s1),len(s2)): ]
         elif len(s1)<len(s2):
           return a+''.join(s2)[min(len(s1),len(s2)): ]
         else:
           return a

但它会产生:

hphehohphlhee

我知道问题是:

for c in s1:
 for d in s2:
  a=a+c+d

但我不知道如何解决它

3 个答案:

答案 0 :(得分:4)

你是对的。你不需要迭代这两个字符串。你可以这样做:

def mangle(s1, s2):
    a = ""
    for i in range(min(len(s1), len(s2))):
        a += s1[i] + s2[i]
    if len(s1) > len(s2):
        return a + s1[min(len(s1), len(s2)):]
    elif len(s1) < len(s2):
        return a + s2[min(len(s1), len(s2)):]
    return a

assert(mangle('hello','people') == "hpeelolpole")

此程序可以用itertools.izip_longest编写,如下所示:

try:
    from itertools import izip_longest as zip  # Python 2
except ImportError:
    from itertools import zip_longest as zip   # Python 3

def mangle(s1, s2):
    return "".join(c1 + c2 for c1, c2 in zip(s1, s2, fillvalue=''))

assert(mangle('hello','people') == "hpeelolpole")

答案 1 :(得分:0)

import itertools as IT
def roundrobin(*iterables):
    """
    roundrobin('ABC', 'D', 'EF') --> A D E B F C
    http://docs.python.org/library/itertools.html#recipes (George Sakkis)
    """
    pending = len(iterables)
    nexts = IT.cycle(iter(it).next for it in iterables)
    while pending:
        try:
            for n in nexts:
                yield n()
        except StopIteration:
            pending -= 1
            nexts = IT.cycle(IT.islice(nexts, pending))

print(''.join(roundrobin('hello','people')))

产量

hpeelolpole

答案 2 :(得分:0)

您需要遍历字符串并从同一索引中获取字符。

def mangle(s1,s2):
    a=""
    small = min(len(s1),len(s2))
    for i in range(0,small):        
        a = a + s1[i] + s2[i]
    if small is len(s1):
        a = a + ''.join(s2[i+1:])
    else:
        a = a + ''.join(s1[i+1:])
    return a