交换字符串中的字符对

2024-10-01 22:43:28 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我对Python还很陌生,不知道该怎么做:

我需要取一个字符串,比如“ABAB_uab”,将其转换为一个列表,然后取我要移动的对的前导索引,并将该对与该字符串交换。我认为输出应该是这样的:

move_chars('ABAB__AB', 0) '__ABABAB'

还有一个例子:

move_chars('__ABABAB', 3) 'BAA__BAB'

真的不知道怎么做。在


Tags: 字符串列表moveab例子bab前导chars
3条回答

我认为这应该去评论区,但我不能评论,因为缺乏声誉,所以。。。在

您可能希望坚持使用列表索引交换,而不是使用.pop()和{}。.pop()可以从任意索引中移除元素,但一次只能移除一个元素,.append()只能将元素添加到列表的末尾。所以它们是非常有限的,在这类问题中使用它们会使代码复杂化。在

所以,好吧,最好还是用索引交换。在

诀窍是使用列表切片来移动部分字符串。在

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))

Python字符串是不可变的,因此不能真正修改字符串。相反,你要做一个新的字符串。在

如果希望能够修改字符串中的单个字符,可以将其转换为一个字符列表,对其进行处理,然后将该列表重新联接为字符串。在

chars = list(str)
# work on the list of characters
# for example swap first two
chars[0], chars[1] = chars[1], chars[0]
return ''.join(chars)

相关问题 更多 >

    热门问题