我正在尝试使用三个参数的方法。字符串,索引和长度。我正在尝试创建一个无限的字符串。
示例: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个索引。书中“b”左边的所有添加的字符都有负的索引。
没有任何循环怎么样?
我们有3部分: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
可能更友好使用。但是,如果您不想使用外部库,则可以考虑使用此解决方案。
只需使用modulo %
将索引“规范化”为字符串的长度:
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'
您可以使用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'