在python中拆分和合并字符串

时间:2015-03-23 20:34:16

标签: python

我想写一个函数..实际上让我引用这个例子:

def return_path(item_id):
    # return item_id

print return_path(1234567) # 67/45/23/1234567
print return_path(1) # 00/00/01/1
print return_path(12345678) # 78/56/34/12345678

我已经能够找到按顺序编写它(但它不完全正确)

def return_path(item_id):
    path = ''
    path.extend(re.findall(r'.{1,2}',str(item_id) ,re.DOTALL))
    path.append(str(item_id))
    return os.path.join(*path)

3 个答案:

答案 0 :(得分:3)

您缺少一些规则:

  • 只计算最右边的6位数。

  • 带<的数字6位需要填充;在左边添加零,直到你有一个偶数个数字,在第五个数字之前有一个奇数的最后一个数字。

  • 数字已配对,然后从最高到最低反转。

这就完成了所有这些:

def return_path(item_id):
    path = []
    # pad with zeros, grab only the last 6 digits
    str_id = format(item_id, '06d')[-6:]
    # any extra zero pairs at the start are in the path first
    while str_id.startswith('00'):
        path.append('00')
        str_id = str_id[2:]
    # for an odd number of padding zeros, swap out the 0 to the last digit
    if str_id[0] == '0':
        str_id = str_id[1:-1] + '0' + str_id[-1:]
    # grab digits in pairs starting at the end
    path += [str_id[i:i + 2] for i in range(len(str_id) - 2, -1, -2)]
    path.append(str(item_id))
    return os.path.join(*path)

演示:

>>> return_path(1)
'00/00/01/1'
>>> return_path(12)
'00/00/12/12'
>>> return_path(123)
'00/03/12/123'
>>> return_path(1234)
'00/34/12/1234'
>>> return_path(12345)
'05/34/12/12345'
>>> return_path(123456)
'56/34/12/123456'
>>> return_path(1234567)
'67/45/23/1234567'
>>> return_path(12345678)
'78/56/34/12345678'

答案 1 :(得分:1)

我将最后的6分为2分组,将其反转,用零填充,然后将其分组为2,并将其用作最终路径。

import itertools

def grouper(iterable, n):
    groups = [iter(iterable)] * n
    return [''.join(group) for group in itertools.zip_longest(*groups,
                                                              fillvalue='')]

def return_path(item_id):
    item_id = str(item_id)
    concat_path = ''.join(list(grouper(item_id[-6:], 2))[::-1])
    zero_padded_path = "000000" + concat_path
    final_path_groups = grouper(zero_padded_path[-6:], 2)
    return '/'.join(["{}/{}/{}".format(*final_path_groups), item_id])

样本

In [85]: return_path(123)
Out[85]: '00/03/12/123'
In [86]: return_path(1)
Out[86]: '00/00/01/1'
In [87]: return_path(123456789)
Out[87]: '89/67/45/123456789'

答案 2 :(得分:1)

编辑:我更改了if语句,因为额外的空间实际上需要在最后一个数字之前,而不是第一个数字。这样它就会返回00/03/12/123而不是00/23/01

def return_path(item_id):
    if len(item_id) % 2 != 0:
        item_id = item_id[:-1] + ' ' + item_id[-1]
    path = ['{:6}'.format(item_id)[-6:].replace(' ', '0')[x-2:x] for x in range(2, 7, 2)]
    path.reverse()
    return '/'.join(path) + '/{}'.format(item_id.replace(' ',''))

解释

if子句通过在最后一位数之前添加一个空格来确保该字符串是偶数个字符。

这是一个非常长的行(不包括path =

的解释
['{:6}'.format(item_id)[-6:].replace(' ', '0')[x-2:x] for x in range(2, 7, 2)]
[                                                     for x in range(2, 7, 2)] Begins list comprehension
 '{:6}'.format(item_id)                                                        Gets item_id with added spaces if needed
                       [-6:]                                                   Gets last 6 characters
                            .replace(' ', '0')                                 Changes all spaces to 0's
                                              [x-2:x]                          Slices [0:2], [2:4], [4:6] (see list comprehension)

这样可以将最后6位数字切成2个字符的段。然后它.reverse(),最后它返回与/相关联的列表,并在末尾附加item_id

编辑2:如果您想要非常喜欢,可以使用以下内容替换if语句后面的所有内容(当然不包括item_id =行):< / p>

return '/'.join(['{:6}'.format(item_id)[-6:].replace(' ', '0')[x-2:x] for x in range(2, 7, 2)][::-1]) + '/{}'.format(item_id.replace(' ', ''))
相关问题