在python中将一个字符串分成两半

时间:2016-09-03 21:07:58

标签: python

这是我的问题:

F. front_back
# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same length.
# If the length is odd, we'll say that the extra char goes in the front   half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a and b, return a string of the form
#  a-front + b-front + a-back + b-back

这是我的答案:

def front_back(a, b):
  s = ""
  if len(a) % 2 == 0:
      s = s + a[:len(a) / 2]
      if len(b) % 2 == 0:
          s = s + b[:len(b) / 2]
          s = s + a[len(a) / 2:]
          s = s + b[len(b) / 2:]
      else:
          s = s + b[:len(b) / 2 + 1]
          s = s + a[len(a) / 2 + 1:]
          s = s + b[len(b) / 2 + 1:]
  else:
      s = s + a[:len(a) / 2 + 1]
      if len(b) % 2 == 0:
          s = s + b[:len(b) / 2]
          s = s + a[len(a) / 2:]
          s = s + b[len(b) / 2:]
      else:
          s = s + b[:len(b) / 2 + 1]
          s = s + a[len(a) / 2 + 1:]
          s = s + b[len(b) / 2 + 1:]
  return s

这个答案对所有字符串都不起作用,我不明白是什么问题。

4 个答案:

答案 0 :(得分:1)

因此,如果使用round to truncate,则不需要检查被分割成两半的字符串是否具有偶数个字符。你想要的是递归地执行一步。

def divideInHalf(str):
    return str[:round(len(str)/2)], str[round(len(str))/2:]

def main():
    str = "abcde"
    a,b = divideInHalf(str)
    front_a,front_b = divideInHalf(a);
    back_a,back_b = divideInHalf(b);

我个人认为这更清洁,可重复使用,但是如果你真的希望它将字符串除以四分之一,这就是方法。

def cutInFour(str):
    a = str[:round(len(str)/2)]
    b = str[round(len(str))/2:]
    return a[:round(len(a)/2)],a[round(len(a))/2:],b[:round(len(b)/2)],b[round(len(b))/2:]

def main():
   str = "abcde"
   front_a,front_b,back_a,back_b = cutInFour(str)

答案 1 :(得分:1)

另一种替代方法:

sample_string = "abcde"

def front_back(a, b):
    half_way_a = (len(a) + 1) / 2
    half_way_b = (len(b) + 1) / 2
    output = "{} + {} + {} + {}".format(a[:half_way_a], b[:half_way_b], a[half_way_a:], b[half_way_b:])
    return output

答案 2 :(得分:0)

尝试编写一个新函数,它接受一个字符串并返回前后两半。然后你的front_back函数可以使用这个新函数来分割两个字符串并轻松地重新组合它们。

答案 3 :(得分:0)

divmod可用于将拆分分成两半。将 split 逻辑包装在另一个函数中使其可重用。因此,字符串被分割然后重建:

def split(s):
    half, rem = divmod(len(s), 2)
    if rem:
        half += 1
    return s[:half], s[half:]

def front_back(a, b):
    front_a, back_a = split(a)
    front_b, back_b = split(b)
    return front_a + front_b + back_a + back_b