[英]Iterate through a string forwards and backwards, extracting alternating characters
I'm studying python and there's a lab I can't seem to crack.我正在研究 python 并且有一个我似乎无法破解的实验室。 We have a line eg shacnidw
, that has to be transformed to sandwich
.我们有一条线,例如shacnidw
,它必须被转换成sandwich
。 I somehow need to iterate with a for
loop and pick the letters with odd indexes first, followed by backward even indexes.我不知何故需要使用for
循环进行迭代,并首先选择具有奇数索引的字母,然后是后向偶数索引。 Like pick a letter with index 1,3,5,7,8,6,4,2.就像选择一个索引为 1,3,5,7,8,6,4,2 的字母。
It looks pretty obvious to use a list or slices, but we aren't allowed to use these functions yet.使用列表或切片看起来很明显,但我们还不允许使用这些函数。 I guess the question is just how do I do it?我想问题是我该怎么做?
I hope I am understanding your question right.我希望我能正确理解你的问题。 Check the below code.检查下面的代码。
s = 'shacnidw'
s_odd = ""
s_even = ""
for i in range(len(s)):
if i%2 == 0:
s_even += s[i]
for i in range(len(s), 0, -1):
if i%2 == 1:
s_odd += s[i]
print(s_even + s_odd)
I hope it might help.我希望它可能会有所帮助。
Programming is all about decomposing complex problems into simpler ones.编程就是将复杂的问题分解为更简单的问题。 Try breaking it down into smaller steps.试着把它分解成更小的步骤。
for
loop?首先,你能在for
循环中生成数字 1、3、5、7 吗?Tackling those two steps ought to get you on the right track.解决这两个步骤应该会让你走上正轨。
Your text looks to be in a specific pattern that can be achieved using the following syntax.您的文本看起来是可以使用以下语法实现的特定模式。
1, 3, 5, 7: for n in range(1, size, 2): steps of 2 in forward direction 1, 3, 5, 7:对于范围内的 n(1, size, 2):正向步长为 2
8, 6, 4, 2: for m in range(size, 0, -2): steps of 2 in reverse direction 8, 6, 4, 2:对于m in range(size, 0, -2):反方向步长2
By building the string with the above indices we can easily arrive at the intended result.通过使用上述索引构建字符串,我们可以很容易地得到预期的结果。
string = 'shacnidw'
result = ''
size = len(string) - 1
for n in range(0, size, 2):
result += string[n]
for m in range(size, 0, -2):
result += string[m]
print(result)
Result结果
sandwich
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.