python - 将句子中的单词更改为特殊字符
问题描述
我正在尝试将句子中的某些单词更改为特殊字符,但没有得到所需的输出。我也尝试过使用 replace 方法,它不会替换所有内容,但只能替换第一个单词。
new_sentence = ''
sentence = input('Enter your word:')
for char in sentence:
if 'the' in sentence:
new_sentence += '~'
elif 'as' in sentence:
new_sentence += '^'
elif 'and' in sentence:
new_sentence += '+'
elif 'that' in sentence:
new_sentence += '$'
elif 'must' in sentence:
new_sentence += '&'
elif 'Well those' in sentence:
new_sentence += '% #'
else:
new_sentence += sentence
print(new_sentence)
这就是我运行它时发生的情况。
Enter your word:the as much and
~~~~~~~~~~~~~~~
解决方案
您可以将您的字符修改存储在字典中,然后replace()
在 for 循环中使用它们,如下所示:
sentence = 'This is the sentence that I will modify with special characters and such'
modifiers = {'the': '~', 'as': '^', 'and': '+', 'that': '$', 'must': '&', 'Well those': '% #'}
for i, v in modifiers.items():
sentence = sentence.replace(i, v)
回报:
This is ~ sentence $ I will modify with special characters + such
推荐阅读
- java - 我无法在 windowbuilder 中编辑我的代码,也无法删除 JTable,它一直显示旧的设计控制台
- scala - Scalacache 从使用 memoizeF 设置的缓存中删除
- java - 如何在代码中在 Spring Boot 中配置 Flyway
- android - Flutter AR - 绘制平面
- php - 在我自己的网站中的嵌入式 youtube 视频中设置时间线
- hyperledger-fabric - 如何安装 Fabric Mir BFT 共识?
- python - 计算数据框中列表长度的乘积并存储在新列中
- rxjs - 订阅方法中的可观察取消订阅
- azure-active-directory - 通过 API 创建 Microsoft 团队会议
- wordpress - Gantry 5 中的响应块大小