def move_chars(s, index):
to_index = s.find('__') # index of destination underscores
chars = list(s) # make mutable list
to_move = chars[index:index+2] # grab chars to move
chars[index:index+2] = '__' # replace with underscores
chars[to_index:to_index+2] = to_move # replace underscores with chars
return ''.join(chars) # stitch it all back together
print(move_chars('ABAB__AB', 0))
print(move_chars('__ABABAB', 3))
我认为这应该去评论区,但我不能评论,因为缺乏声誉,所以。。。在
您可能希望坚持使用列表索引交换,而不是使用}。
.pop()
和{.pop()
可以从任意索引中移除元素,但一次只能移除一个元素,.append()
只能将元素添加到列表的末尾。所以它们是非常有限的,在这类问题中使用它们会使代码复杂化。在所以,好吧,最好还是用索引交换。在
诀窍是使用列表切片来移动部分字符串。在
Python字符串是不可变的,因此不能真正修改字符串。相反,你要做一个新的字符串。在
如果希望能够修改字符串中的单个字符,可以将其转换为一个字符列表,对其进行处理,然后将该列表重新联接为字符串。在
相关问题 更多 >
编程相关推荐