How can I replace string in list using dictionary?
I have
text = ["h#**o "," &&&orld"]
replacement = {"#":"e","*":"l"," ":"w","&":""}
I want:
correct = ["Hello World"]
I have try:
def correct(text,replacement):
for word, replacement in replacement.items():
text = text.replace(word, replacement)
But: AttributeError: 'list' object has no attribute 'replace'
CodePudding user response:
What you have is mostly correct except your correct
function seems to be wanting to correct only a single str
(e.g. "h#**o "
=> "hellow"
), whereas your variable text
is currently a list
or str
s. So if you want to get "hellow world"
you need to call correct
multiple times to get a list of corrected words, which you can then join into a string.
Try this runnable example!
#!/usr/bin/env python
words = ["h#**o "," &&&orld"]
replacement = {"#":"e","*":"l"," ":"w","&":""}
def correct(text,replacement):
for word, replacement in replacement.items():
text = text.replace(word, replacement)
return text
def correct_multiple(words, replacement):
new_words = [correct(word, replacement) for word in words] # get a list of results
combined_str = " ".join(new_words) # join the list into a string
return combined_str
output = correct_multiple(words, replacement)
print(f"{output=}")
<script src="https://modularizer.github.io/pyprez/pyprez.min.js"></script>
CodePudding user response:
You can do this too:
text = ["h#**o "," &&&orld"]
replacement = {"#":"e","*":"l"," ":"w","&":""}
string1 = " ".join(text) # join the words into one string
string2 = string1.translate(string1.maketrans(replacement))
string3 = string2.title()
print(string1 '\n' string2 '\n' string3)
# h#**o &&&orld
# hellow world
# Hellow World
I've separated the proceedings into 3 successive steps to demonstrate the effect of each step.
CodePudding user response:
text
is a LIST of strings, not a string. You can't call string methods on it.
text[0].replace()
would be a thing...