-1

I have a string "111222333" inside a CSV file. I would like to convert this into something like "\111\222\333"

Currently my python code is :

refcode = "111222333"
returnstring = "\\" + refcode[:3] + "\\" + refcode[3:6] + "\\" + refcode[-3:] + "\\"

I know there must be a better way to do this. May I know what are the better ways to do the same thing. Please help.

1 Answers1

0

You could use re for that:

import re
refcode = "111222333"

returnstring = '\\'.join(re.match('()(\S{3})(\S{3})(\S{3})()', refcode).groups())

Explanation: You have a string of 9 characters (let's say they are not any kind of whitespace chatacters, so we could represent it with \S).
We create a matching regexp using it, so (\S{3}) is a group of three sequential non-space characters (like letters, numbers, exclamation marks etc.).

(\S{3})(\S{3})(\S{3}) are three groups with 3 characters in each one.

If we call .groups() on it, we'll have a tuple of the matched groups, just like that:

In [1]: re.match('(\S{3})(\S{3})(\S{3})', refcode).groups()
Out[1]: ('111', '222', '333')

If we join it using a \ string, we'll get a:

In [29]: print "\\".join(re.match('(\S{3})(\S{3})(\S{3})', refcode).groups())
111\222\333

But you want to add the backslashes on the both sides of the string as well! So we could create an empty group - () - on the each side of the regular expression.

Igor Hatarist
  • 5,234
  • 2
  • 32
  • 45