因此,对于字符串“hello”,结果将是:
hello
ehllo
elhlo
ellho
elloh # here it use this string from the last result, instead of the original one
leloh
lleoh
...
hello # last result
在上面的示例中,原始字符串出现了两次,尽管我说过“不重用原始字符串”,但请记住,它只是为了更好地说明示例。
import sys
def move_char_by_increment(string, char, increment):
char_list = list(string)
old_index = char_list.index(char)
char = char_list.pop(old_index)
new_index = old_index + increment
char_list.insert(new_index, char)
return ''.join(char_list)
string = sys.argv[1]
total_char_input = len(string)
for char in string:
for i in range(0,total_char_input):
print(move_char_by_increment(string, char, i))
sys.exit()
这成功地将字符一个接一个地移动到字符串的末尾,但是,它确实重用了原始字符串,而不是像上面的示例中那样做…我找不到一种方法让它做我想做的事情。