簡體   English   中英

如何有效地用其他元素替換字符串中的多個元素?

[英]How do you replace multiple elements in a string with other elements efficiently?

給定一個字符串,說 'ABCD',你應該用 'E' 和 'J' 替換 'A' 和 'C'。 你將如何替換它並將輸出作為python中的字符串返回?

使用 replace() 方法

string = 'ABCD'
#Use dictionary of characters to be replaced
chars_to_replace = {
    'A':'E',
    'C':'J'
}
for key, value in chars_to_replace.items():
    # Use the replace() method
    string = string.replace(key, value)
print(string)

使用 for 循環

string = "ABCD"
chars_to_replace = {
    'A':'E',
    'C':'J'
}
new_string = ''
# Use for loop to iterate over all chars in string
for i in string:
    # Check if character is in dict key
    if i in chars_to_replace.keys():
        # If yes, replace values of those chars
        # and add to new_string
        new_string += chars_to_replace[i]
    else:
        # If not, just add them to new_string
        new_string += i
print(new_string)

使用str.translate()方法:

string = 'ABCD'
m = str.maketrans({'A': 'E', 'C': 'J'})

print(string.translate(m))

輸出 :

EBJD

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM