简体   繁体   English

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

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

Given a string, say 'ABCD' and you are supposed to replace 'A' and 'C' with 'E' and 'J'.给定一个字符串,说 'ABCD',你应该用 'E' 和 'J' 替换 'A' 和 'C'。 How would you replace this and return the output as a string in python?你将如何替换它并将输出作为python中的字符串返回?

Using the replace() method使用 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)

Using a for loop使用 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)

Use str.translate() method :使用str.translate()方法:

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

print(string.translate(m))

output :输出 :

EBJD

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM