在字符串中交换两个字符的多个实例

huangapple go评论65阅读模式
英文:

Swapping multiple instances of two characters in a string

问题

I'd like to find, if possible, a more succinct or elegant way to swap every occurrence of two specific characters in a string, but still readable and easy to understand, i.e. something akin to a, b = b, a for variables.

For example, say I want to swap the characters X and Y in the following string: "AAAXYAYXAXX""AAAYXAXYAYY".

The way I'm doing it currently is:

text = text.replace("B", "tempB").replace("A", "B").replace("tempB", "A")

but I'm wondering if there may be a better way.

英文:

I'd like to find, if possible, a more succinct or elegant way to swap every occurrence of two specific characters in a string, but still readable and easy to understand, i.e. something akin to a, b = b, a for variables.

For example, say I want to swap the characters X and Y in the following string : "AAAXYAYXAXX""AAAYXAXYAYY".

The way I'm doing it currently is

text = text.replace("B", "tempB").replace("A", "B").replace("tempB", "A")

but I'm wondering if there may be a better way.

答案1

得分: 1

你可以使用 translatemaketrans

def swap_characters(text, char1, char2):
    return text.translate(str.maketrans(char1 + char2, char2 + char1))

str.maketrans() 创建一个翻译表,将 char1 映射到 char2,反之亦然。然后,text.translate() 将翻译表应用于输入字符串。

英文:

You can use translate and maketrans.

def swap_characters(text, char1, char2):
    return text.translate(str.maketrans(char1 + char2, char2 + char1))

str.maketrans() creates a translation table that maps char1 to char2 and vice versa. Then, text.translate() applies the translation table to the input string

huangapple
  • 本文由 发表于 2023年6月9日 01:09:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76434223.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定