Py学习  »  Python

在python中如何根据索引和长度来无限字符串?

shadow.T • 6 年前 • 1957 次点击  

我试着做一个有三个参数的方法。字符串、索引和长度。 我正在尝试创建一个无限字符串。

例子: method("book",-3,9)

输出: ookbookbo

例2: method("book",-5,15)

输出2 kbookbookbookbo

我的代码:

def create_sequence(string, index, length):
    positive_index = abs(index)
    l = list(string)
    end = ""
    print(length- positive_index - len(l))
    for i in range(length- positive_index - len(l)):

        end += l[i]
    output = ''.join([string,end])

我的逻辑是:字符串将一直被使用,所以我只需要得到序列的右端部分和开始(左侧)部分,然后将它们连接在一起。只要 length - positive_index - len(l) 小于或等于字符串长度。我也不知道如何得到原始字符串之前的序列部分。

我是python的初学者,任何帮助都非常感谢。

编辑:我希望我的输入字符串是基础。在书中,每一个字母都有0,1,2和3个索引。书中“0”即“B”左边的所有字符都有负指数。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/41134
文章 [ 3 ]  |  最新文章 6 年前
han solo
Reply   •   1 楼
han solo    7 年前

你可以使用 itertools 创造相似的东西

>>> import itertools
>>> x = itertools.islice(itertools.cycle("book"), 1,5)
>>> ''.join(x)
'ookb'
>>> x = itertools.islice(itertools.cycle("book"), 3,9)
>>> ''.join(x)
'kbookb'
>>> x = itertools.islice(itertools.cycle("book"), 3,10)
>>> ''.join(x)
'kbookbo'

根据@tobias_k处理负面指数的建议更新,

>>> def mkseq(string, index, length):
...   return ''.join(itertools.islice(itertools.cycle(string), index % len(string), index % len(string) + length))
... 
>>> mkseq("book", -3, 9)
'ookbookbo'
tobias_k
Reply   •   2 楼
tobias_k    7 年前

只是用模 % 要将索引“规范化”为字符串长度:

def create_sequence(string, start, length):
    return ''.join(string[i % len(string)] for i in range(start, start + length))

>>> create_sequence("book", -3, 9)
'ookbookbo'
>>> create_sequence("book", -5, 15)
'kbookbookbookbo'
Karls
Reply   •   3 楼
Karls    7 年前

不绕圈子怎么样?

我们有三部分: Begin of string , Middle (repetition of word "book") End

def create_sequence(string, index, length):
    word_length=len(string)
    string_repetition=((length+index)//word_length+(-index)//word_length) #How many full strings we have
    string_end=(length+index)%word_length #How manny letters are left after last full word
    inf_string_start= string[length-string_repetition*word_length:]
    inf_string_mid=string_repetition*string#MID
    inf_string_end=string[:string_end] #END
    inf_string=inf_string_start+inf_string_mid+inf_string_end #concatenation

    return inf_string

然而 itertools 使用起来可能更友好。但如果不想使用外部libs,可以考虑使用此解决方案。