Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I try to put this steps in one, but it doesnt work

w = re.sub('[0-9]', r'9', w)
w = re.sub('[A-Z]', r'X', w)
w = re.sub('[a-z]', r'x', w)

Does anybody knows how to make from such strings as XXxxxx999 --> Xx9.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
649 views
Welcome To Ask or Share your Answers For Others

1 Answer

You may use a callback method as a replacement argument like this:

import re

rx = r'([0-9]+)|([A-Z]+)|[a-z]+'
w = "XXxxxx999"

def repl(m):
    if m.group(1):       # if ([0-9]) matched
        return '9'       # replace with 9
    elif m.group(2):     # if ([A-Z]) matched
        return 'X'       # replace with X
    else:                # if ([a-z]) matched
        return 'x'       # replace with x

print(re.sub(rx, repl, w)) # => Xx9

See the Python demo.

The regex matches:

  • ([0-9]+) - Group 1: 1+ digits
  • | - or
  • ([A-Z]+) - Group 2: 1+ uppercase letters
  • | - or
  • [a-z]+ - 1+ lowercase letters.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...