英文:
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
你可以使用 translate
和 maketrans
。
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论