2

I have a few lines of string e.g:

AR0003242303
TR0402304004
CR0402340404

I want to create a dictionary from these lines.

And I need to create change it in regex to:

KOLAORM0003242303
KOLTORM0402304004
KOLCORM0402340404

So i need to split first 2 characters, before PUT KOL, between PUT O, and Afer second char put M. How can i reach it. Through many attempts I lose patience with the regex and unfortunately I now I have no time to learn it better now. Need some result now :(

Could someone help me with this case?

0

4 Answers 4

5

Using re.sub --> re.sub(r"^([A-Z])([A-Z])", r"KOL\1O\2M", string)

Ex:

import re

s = ["AR0003242303", "TR0402304004", "CR0402340404"]
for i in s:
    print( re.sub(r"^([A-Z])([A-Z])", r"KOL\1O\2M", i) )

Output:

KOLAORM0003242303
KOLTORM0402304004
KOLCORM0402340404
Sign up to request clarification or add additional context in comments.

2 Comments

Thank u very much for help. For better understand: ([A-Z])([A-Z]) means only A-Z characters... KOL is that what i need to put in first step, but how works \10\2M ?
\1 & \2 are the groups in the regex. --> ([A-Z])([A-Z])
2

You don't need regex for this, you can do it with getting the list of characters from the string, recreate the list, and join the string back

def get_convert_s(s):
    li = list(s)
    li = ['KOL', li[0], '0', li[1], 'M', *li[2:]]
    return ''.join(li)

print(get_convert_s('AR0003242303'))
#KOLA0RM0003242303
print(get_convert_s('TR0402304004'))
#KOLT0RM0402304004
print(get_convert_s('CR0402340404'))
#KOLC0RM0402340404

Comments

2
import re

regex = re.compile(r"([A-Z])([A-Z])([0-9]+)")

inputs = [
    'AR0003242303',
    'TR0402304004',
    'CR0402340404'
]

results = []
for input in inputs:
    matches = re.match(regex, input)
    groups = matches.groups()
    results.append('KOL{}O{}M{}'.format(*groups))

print(results)

Comments

1

Assuming the length of the strings in your list will always be the same Devesh answers is pretty much the best approach (no reason to overcomplicate it).

My solution is similar to Devesh, I just like writing functions as oneliners:

list = ["AR0003242303", "TR0402304004", "CR0402340404"]

def convert_s(s):
    return "KOL"+s[0]+"0"+s[1]+"M"+s[2:]

for str in list:
   print(convert_s(str));

Altough it returns the same output.

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.