我坚持做以下实验练习:
The first piece we need is a routine that, given a word, will in someway jumble up the order of all but the first and the last characters. Rather than just randomly moving the characters around we will reverse the order of the letters. The following code achieves this:
def jumble(x): return x[len(x)::-1] my_string="Alistair" print(" Reverse ",jumble(my_string))
Copy the above code to a file and run it. Currently it reverses the order of all the characters in "my_string". Modify the code so that the first and last letters of the word are NOT reversed. That is, instead of producing
"riatsilA"
it produces"Aiatsilr"
.
这是我对上述部分的代码:
def jumble(x):
temp0=x[0]
temp_last=x[-1]
x_new=temp0 + x[-2:0:-1] + temp_last
return x_new
my_string="Alistair"
print(" Reverse ",jumble(my_string))
The above routine does not account for leading or trailing white space, punctuation or other characters that might legitimately be part of the character string, but that should not be jumbled up. For example if the string were
" Alistair, "
the result should be" riatsilA, ".
Modify your routine so that only the FIRST contiguous series of alphabetical characters (minus the first and last characters) are reversed. Ensure that the final returned string includes all other leading and trailing characters.
我不知道该怎么做,因为空格和标点符号可以在任何地方出现,我想有两个列表,一个是空白和标点,另一个是“连续的字母字符序列”,使用append方法在每个列表中追加元素,但不确定如何保存索引。Can有人帮我吗?提前谢谢。在
修好了。在
下面的代码片段可以帮助您完成最后一个任务。 如果在字符串的开始或结尾之外的其他地方发现了特殊字符,则对于子集的恢复没有特殊处理。在
将导致以下输出:
' riatsilA, ' =?= ' riatsilA, '
只需返回忽略第一个和最后一个字符是一行代码。 用这个来反转“中间”:t[1:-1][::-1] 然后添加第一个和最后一个字符。在
^{pr2}$编辑
好吧,现在我想我明白你想要什么了:-)
相关问题 更多 >
编程相关推荐