我正在尝试将句子中的某些单词更改为特殊字符,但没有得到所需的输出。我也尝试过使用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
~~~~~~~~~~~~~~~
答案 0 :(得分:3)
您可以将字符修改存储在字典中,然后在循环中使用@RunWith(SpringJUnit4ClassRunner::class)
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.NONE,
classes = [CacheService::class]
)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
class CacheIntegrationTest {
// Tests
@EnableCaching
@TestConfiguration
class CacheTestConfiguration {
@Bean
fun cacheManager(): CacheManager = CaffeineCacheManager()
}
}
来应用它们,如下所示:
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)
答案 1 :(得分:1)
@ rahlf23具有正确的方法,但以防万一您想使用当前的实现:
如果将句子拆分成单个单词,然后遍历这些单词并检查单词本身,而不是检查输入字符串中的每个字符并检查字符串中是否存在要替换的单词,您将在正确的轨道上
for word in sentence.split():
if word.lower() == 'the':
new_sentence += '~'
...