10. String operations

https://note.nkmk.me/en/python-str-replace-translate-re-sub/

Here's how to replace strings in Python.

  • Replace substrings: replace()

    • Specify the maximum count of replacements: count

    • Replace multiple different substrings

    • Replace newline character

  • Replace multiple different characters: translate()

  • Replace with regular expression: re.sub(), re.subn()

    • Replace multiple substrings with the same string

    • Replace using the matched part

    • Get the count of replaced parts

  • Replace by position: slice

Regular Expression

re.search()

for text in df['simplified'][:3]:
    hit = re.search(p, text)
    print(hit)
    print(hit.start(), hit.end())
    print(hit.group())

re.finditer()

因為是iterator的關係,可用

hits = re.finditer(p, "這個哈哈哈美帝真的北美很討厭")
# print(next(hits))
for h in hits:
    print(h.start(), h.end(), h.group())

Last updated