search

Home  >  Q&A  >  body text

string - Python string case-insensitive replacement

Replace hello in Hello World, HELLO PYTHON with My.
Since the replace() function replacement is case-sensitive, how can Python implement string replacement without case sensitivity?

伊谢尔伦伊谢尔伦2710 days ago1594

reply all(2)I'll reply

  • 仅有的幸福

    仅有的幸福2017-06-28 09:26:52

    Reference article: Issues related to Python string operations

    String case-insensitive replacement
    str.replace(old, new[, max])The replacement is case-sensitive. Case-insensitive replacement requires the regular expression re.sub() with the re.IGNORECASE option.

    >>> import re
    >>> reg = re.compile(re.escape('hello'), re.IGNORECASE)
    >>> reg.sub('My', 'Hello World, HELLO PYTHON')
    'My World, My PYTHON'

    reply
    0
  • 阿神

    阿神2017-06-28 09:26:52

    import re
    
    s = 'Hello World, HELLO PYTHON'
    print re.sub(r'(?i)hello', 'My', s)
    

    reply
    0
  • Cancelreply