Python 将句子中的单词改为特殊字符

Python 将句子中的单词改为特殊字符,python,Python,我试图将句子中的一些单词改为特殊字符,但没有得到所需的输出。此外,我还尝试了使用replace方法,该方法除了替换第一个单词外,并没有替换所有单词 new_sentence = '' sentence = input('Enter your word:') for char in sentence: if 'the' in sentence: new_sentence += '~' elif 'as' in sentence: new_sente

我试图将句子中的一些单词改为特殊字符,但没有得到所需的输出。此外,我还尝试了使用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
~~~~~~~~~~~~~~~

您可以将字符修改存储在字典中,然后在for循环中使用
replace()
应用它们,如下所示:

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

@rahlf23有正确的方法,但以防您想使用当前的实现:

如果您将句子拆分为单个单词,然后迭代这些单词并检查单词本身,而不是检查输入字符串中的每个字符并检查字符串中是否存在任何要替换的单词,您将走上正确的道路

for word in sentence.split():
    if word.lower() == 'the':
    new_sentence += '~'
    ...

你确定你的替换方法正确吗?如果你的句子包含“the”,那么只有你的第一个条件会触发,其余的不会,但它仍然会循环输入字符串中的所有字符,并为每个字符触发你的第一个条件,因为它会循环遍历每个字母,所以t,h,e,等等。。。如果你想循环遍历所有单词,首先使用
句子.strip()
生成一个包含所有单词的列表,所以只需对句子中的单词使用
。strip()
就可以得到你想要的结果,@daliseiyy你想要的是
句子.split()
而不是
。strip()
,但这仍然是非常低效的。