在任意索引和步骤(Python)处一起拉链字符串



我在Python 2.7中工作。我正在尝试创建一个函数,该函数可以从任意索引开始,并以任意步骤从较大的字符串中划分为较大的字符串。

例如,我可能想将字符串 @#*#*划为较大的字符串TNAXHAXMKQWGZESEJFPYDMYP,从5 th 字符,步骤为3。结果字符串应为:

TNAXHAX@MK#QW*GZ#ES*EJFPYDMYP

我想出的工作功能是

#Insert one character of string every nth position starting after ith position of text
text="TNAXHAXMKQWGZESEJFPYDMYP"
def zip_in(string,text,i,n):
    text=list(text)
    for c in string:
        text.insert(i+n-1,c)
        i +=n
    text = ''.join(text)
    print text

此功能会产生所需的结果,但我觉得它不像它那样优雅。

此外,我希望它足够通用一个角色一次带有向后步骤。

例如,从22 nd 位置开始,我可能想将字符串 @#*#*拉到较大的字符串TNAXHAXMKQWGZESEJFPYDMYP中,步骤为-3。结果字符串应为:

TNAXHAXMKQW*GZ#ES*EJ#FP@YDMYP

使用当前功能,我可以通过设置 n 负数来做到这一点,但是如果我想要-3的步骤,则需要将 n as -2设置为-2。

所有这些都使我提出了我的问题:

是否有更优雅(或Pythonic)实现我的终点?


这里有一些相关问题,这些问题没有提供一般答案:

pythonic方法在字符串中插入每2个元素
在每个nth元素之后,在python列表中插入元素
在N&一起合并两个字符串X

您可以使用itertoolsmore_itertools库中的一些功能(请确保拥有它们)并组合它们以获得结果:chunkedizip_longest

# Parameters
s1 = 'ABCDEFGHIJKLMNOPQ' # your string
s2 = '@#@#' # your string of elements to add
int_from = 4 # position from which we start adding letters
step = 2 # we will add in elements of s2 each 2 letters
return_list = list(s1)[:int_from] # keep the first int_from elements unchanged
for letter, char in izip_longest(chunked(list(s1)[int_from:], step), s2, fillvalue=''):
    return_list.extend(letter)
    return_list.append(char)

然后通过:

恢复字符串
''.join(return_list)

输出:

# For the parameters above the output is :
>> 'ABCDEF@GH#IJ@KL#MNOPQ'

izip_longest(chunked(list(s1)[int_from:], step), s2, fillvalue='')返回什么?

for letter, char in izip_longest(chunked(list(s1)[int_from:], step), s2, fillvalue=''):
    print(letter, char)
>> Output
>> (['E', 'F'], '@')
   (['G', 'H'], '#')
   (['I', 'J'], '@')
   (['K', 'L'], '#')
   (['M', 'N'], '')
   (['O', 'P'], '')
   (['Q'], '')

相关内容

最新更新