python - Can't act with string's methods on a matched group -
i'm exercising standard regexp:
bill gates → gates, bill so do:
in [21]: re.sub("([^ ]+) (.+)", r"\2".upper() + r", \1", "bill gates") out[21]: 'gates, bill' why doesn't work? how 1 applies string methods matched string?
you uppercasing (part of) replacement pattern, not actual replacement result.
the r"\2".upper() + r", \1" expression results in value "\\2, \\1" before passing re.sub().
to dynamically process match groups, you'll need apply changes in function passed .sub() instead of replacement pattern:
def uppercase_last(match): return "{}, {}".format(match.group(2).upper(), match.group(1)) re.sub("([^ ]+) (.+)", uppercase_last, "bill gates") demo:
>>> import re >>> def uppercase_last(match): ... return "{}, {}".format(match.group(2).upper(), match.group(1)) ... >>> re.sub("([^ ]+) (.+)", uppercase_last, "bill gates") 'gates, bill' alternatively, don't use regular expressions @ all:
>>> name = 'bill gates' >>> first, rest = name.split(none, 1) >>> "{}, {}".format(rest.upper(), first)
Comments
Post a Comment