Using Python's `re` module to set all characters lowercase
I'm using the re library to normalize some text. One of the things I want to do is replace all u开发者_开发知识库ppercase letters in a string with their lower case equivalents. What is the easiest way to do this?
>>> 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
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
.)
精彩评论