如何使用字典替換串列中的字串?
我有
text = ["h#**o "," &&&orld"]
replacement = {"#":"e","*":"l"," ":"w","&":""}
我想:
correct = ["Hellow
World"]
我嘗試過:
def correct(text,replacement):
for word, replacement in replacement.items():
text = text.replace(word, replacement)
但是: AttributeError: 'list' 物件沒有屬性 'replace'
uj5u.com熱心網友回復:
你所擁有的大部分是正確的,除了你的correct函式似乎只想更正一個str(例如"h#**o "=> "hellow"),而你的變數text當前是 a list或strs。因此,如果您想獲取,則"hellow world"需要correct多次呼叫以獲取更正單詞的串列,然后您可以將其加入字串中。
試試這個可運行的例子!
#!/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>
uj5u.com熱心網友回復:
你也可以這樣做:
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
我將程式分成 3 個連續的步驟來展示每個步驟的效果。
uj5u.com熱心網友回復:
text是字串串列,而不是字串。你不能在它上面呼叫字串方法。
text[0].replace()會是一件事……
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/524460.html
