テキストの検索と置換

Python:
テキストの検索と置換

How to: (方法:)

Let’s see it in action.

text = "Hello, World!"
new_text = text.replace("World", "Python")
print(new_text)

Output:

Hello, Python!

For multiple replacements:

import re

text = "I like cats and cats like me."
pattern = re.compile(r"cats")
new_text = pattern.sub("dogs", text)
print(new_text)

Output:

I like dogs and dogs like me.

Deep Dive (深い潜水)

Searching and replacing text has a long history in computing, dating back to early text editors. Python provides simple methods like str.replace() and powerful ones from the re module.

Alternatives to str.replace() include re.sub() for regular expressions, used for pattern matching. For large-scale text processing, consider pandas DataFrame replace methods or third-party libraries like NLTK for natural language processing.

Implementation details to remember: str.replace() is fine for straightforward substitutions but isn’t suitable for complex patterns. The re module handles these cases, offering more options and control.

See Also (参照する)