1

I have a string like this

        convert_text = "tet1+tet2+tet34+tet12+tet3"

I want to replace digits into character from above string.That mapping list available separately.so,When am trying to replace digit 1 with character 'g' using replace like below

       import re
       convert_text = convert_text.replace('1','g')
       print(convert_text)

output is

      "tetg+tet2+tet34+tetg2+tet3"

How to differentiate single digit and two digit values.Is there is any way to do with Regexp or something else?

3
  • take a look at regex Commented Aug 9, 2017 at 10:10
  • Is "34" a single replacement or two replacements of "3" and "4"? Commented Aug 9, 2017 at 10:13
  • i want to 34 as single replacement Commented Aug 9, 2017 at 10:16

2 Answers 2

3

You can use a regular expression with a callable replacement argument to substitute consecutive runs of digits with a value in a lookup table, eg:

import re

# Input text
convert_text = "tet1+tet2+tet34+tet12+tet3"

# to->from of digits to string
replacements = {'1': 'A', '2': 'B', '3': 'C', '12': 'T', '34': 'X'}

# Do actual replacement of digits to string
converted_text = re.sub('(\d+)', lambda m: replacements[m.group()], convert_text)

Which gives you:

'tetA+tetB+tetX+tetT+tetC'
Sign up to request clarification or add additional context in comments.

Comments

0
import re
convert_text = "tet1+tet2+tet34+tet12+tet3"
pattern = re.compile(r'((?<!\d)\d(?!\d))')
convert_text2=pattern.sub('g',convert_text)

convert_text2 Out[2]: 'tetg+tetg+tet34+tet12+tetg'

You have to use negative lookahead and negative lookbehind patterns which are in between parenthesis

(?!pat) and 
(?<!pat),  

you have the same with = instead of ! for positive lookahead/lookbehind.

EDIT: if you need replacement of strings of digits, regex is

pattern2 = re.compile(r'\d+')

In any pattern you can replace \d by a specific digit you need.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.