Heim  >  Fragen und Antworten  >  Hauptteil

string – Python-String-Ersetzung ohne Berücksichtigung der Groß-/Kleinschreibung

wirdHello World, HELLO PYTHON中的hello替换成My.
Da bei der Ersetzung der Funktion „replace()“ die Groß-/Kleinschreibung beachtet wird, wie kann Python die Zeichenfolgenersetzung ohne Berücksichtigung der Groß-/Kleinschreibung implementieren?

伊谢尔伦伊谢尔伦2669 Tage vor1553

Antworte allen(2)Ich werde antworten

  • 仅有的幸福

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

    参考文章:Python字符串操作相关问题

    字符串不区分大小写替换
    str.replace(old, new[, max])的替换是区分大小写的。不区分大小写替换需要正则表达式re.sub()带上re.IGNORECASE选项。

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

    Antwort
    0
  • 阿神

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

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

    Antwort
    0
  • StornierenAntwort