简体   繁体   English

替换python中的特定单词

[英]Replace specific words in python

If I have a string "this is", and I want to replace "is" to "was".如果我有一个字符串“this is”,并且我想将“is”替换为“was”。 When I use replace ("is", "was") , I got "thwas was", but what i am expecting is "this was", is there any solution?当我使用replace ("is", "was") ,我得到了“thwas was”,但我期待的是“this was”,有什么解决办法吗?

You need to do something more sophisticated than a regular string replace.您需要做一些比常规字符串替换更复杂的事情。 I'd suggest using Regular Expressions ( the re module ), and using the \\b escape sequence to match word boundaries :我建议使用正则表达式( re模块),并使用\\b转义序列来匹配单词边界

import re
re.sub(r"\bis\b", "was", "This is the best island!")

Result: 'This was the best island!'结果: 'This was the best island!'

By using the pattern r"\\bis\\b" instead of just "is" , you ensure that you only match "is" when it appears as a stand-alone word (ie there are no numbers, letters or underscore characters directly adjacent to it in the original string).通过使用模式r"\\bis\\b"而不仅仅是"is" ,您可以确保仅在 "is" 作为独立单词出现时才匹配它(即没有数字、字母或下划线字符直接与它在原始字符串中)。

Here's some more examples of what matches and what doesn't:以下是一些匹配和不匹配的示例:

re.sub(r"\bis\b", "was", "is? is_number? is, isn't 3is is, ,is, is. hyphen-is. &is")

Result: "was? is_number? was, isn't 3is was, ,was, was. hyphen-was. &was"结果: "was? is_number? was, isn't 3is was, ,was, was. hyphen-was. &was"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM