首页 > 解决方案 > 将句子中的单词更改为特殊字符

问题描述

我正在尝试将句子中的某些单词更改为特殊字符,但没有得到所需的输出。我也尝试过使用 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
~~~~~~~~~~~~~~~

标签: python

解决方案


您可以将您的字符修改存储在字典中,然后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

推荐阅读