Using Python's `re` module to set all characters lowercase

Question:

I’m using the re library to normalize some text. One of the things I want to do is replace all uppercase letters in a string with their lower case equivalents. What is the easiest way to do this?

Asked By: oadams

||

Answers:

>>> s = "AbcD"
>>> s.lower()
'abcd'

There is also a swapcase method if you want that.

See: http://docs.python.org/library/stdtypes.html#string-methods

Answered By: Nux

If you really want to use RegEx, you can do this:

import re
def swapcase(s):
  def changecase(m):
    if m.group("lower"):
      return m.group("lower").upper()
    elif m.group("upper"):
      return m.group("upper").lower()
    else:
      return m.group(0)
  return re.sub("(?P<lower>[a-z])|(?P<upper>[A-Z])", changecase, s)
print(swapcase(input()))

EDIT

If you want all lowercase text, try this:

def lower(s):
  import re
  return re.sub("[A-Z]", str.lower, s)

(Note: the re module is not the best choice here. Use string.lower.)

Answered By: Someone
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.