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

Categories

0 votes
70 views
in Technique[技术] by (71.8m points)

python - remove n before a string

I want to remove unrequired r and n at beginning of each upper-case word and number in this string. I tried regex. Not sure if regex or some other method would be helpful here.

This is the code I am trying to use:

text = "nFamily n49 new nTom"

regex_pattern =  re.compile(r'.*n[A-Z][a-z]*|[0-9]*s')
matches = regex_pattern.findall(text)
for match in matches:
    text = text.replace(match," ")
print(text)

Expected output:

Family 49 new Tom
question from:https://stackoverflow.com/questions/65851230/remove-n-before-a-string

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

1 Answer

0 votes
by (71.8m points)

You can use

text = re.sub(r'n(?=[A-Z0-9])', '', text)

See the regex demo.

Details:

  • - here, start of a word
  • n - a n letter
  • (?=[A-Z0-9]) - a positive lookahead that requires an uppercase ASCII letter or a digit to be present immediately to the right of the current location.

See the Python demo:

import re
rx = r"n(?=[A-Z0-9])"
text = "nFamily n49 new nTom"
print( re.sub(rx, '', text) )
# => Family 49 new Tom

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...