[英]Rearranging letters from a list
This may be a bit confusing to read but what I would like to do is take any string and rearrange the letters based on an input from the user of the program. 这可能有点令人困惑,但我想做的是接受任何字符串并根据程序用户的输入重新排列字母。 So for example, line = "Romeo and Juliet", key=3.
例如,line =“Romeo and Juliet”,key = 3。 The encoded line would start with line[0] R, then move 3 characters down to E, then A, then a SPACE.
编码的行将以行[0] R开始,然后将3个字符向下移动到E,然后是A,然后是空格。 Then once i reach the end of the list it would circle back and start with line[1], add 3, and so on until all the characters have been used.
然后,一旦我到达列表的末尾,它将回绕并以行[1]开始,添加3,依此类推,直到所有字符都被使用。 So the end result would be "Rea ltoonJim due".
所以最终结果将是“Rea ltoonJim due”。 I'm assuming this will use a loop and that's the part I'm stuck on.
我假设这将使用循环,这是我坚持的部分。 This is my current code:
这是我目前的代码:
key = int(input("Enter the key: "))
sent = input("Enter a sentence: ")
print()# for turnin
print()
print("With a key of:",key)
print("Original sentence:",sent)
print()
split = list(sent)
for i in range(len(split)):
print(split[0+i*key])
So I have the list set up, and this gives me the first few letters that I need but I get an error: IndexError: list index out of range.
所以我设置了列表,这给了我需要的前几个字母,但是我得到一个错误:
IndexError: list index out of range.
So once it reaches the final character, how would i get it to loop back to split[1]
and continue through? 所以一旦它到达最后一个角色,我将如何让它循环回
split[1]
并继续通过?
String slicing can take a "skip" factor, so: 字符串切片可以采用“跳过”因子,因此:
>>> s = 'Romeo and Juliet'
>>> s[0::3] # every 3rd letter starting from 0
'Rea lt'
>>> s[1::3] # every 3rd letter starting from 1
'oonJi'
Put that in a loop and join them together: 把它放在一个循环中并将它们连接在一起:
>>> ''.join(s[i::3] for i in range(3))
'Rea ltoonJim due'
As a general function: 作为一般功能:
>>> def rearrange(s,skip):
... return ''.join(s[i::skip] for i in range(skip))
...
>>> rearrange(s,3)
'Rea ltoonJim due'
>>> rearrange(s,5)
'R Jtoaumnledio e'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.