1

I have a file that consists of a single line:

a,x,b,c,d,e 

I want to convert this into

a,x,b,x,c,x,d,x,e,x

Is there any easy way to achieve this with python?

4
  • What is the pattern? an x after any letter that is not x or followed by x? Commented Feb 26, 2014 at 11:49
  • its x after any letter thats not x Commented Feb 26, 2014 at 11:57
  • By that definition your original example is wrong. Unless you meant: x after any letter that's not x, unless already followed by x. What should a,x,x,b,x,c,d,e give? Commented Feb 26, 2014 at 12:01
  • That pattern wont occur..The input is specific which i am parsing from an html table ..lets say a is the name of class I am taking and x is grade Commented Feb 26, 2014 at 12:05

2 Answers 2

1
 my_file = open(filename)
 data = my_file.read()
 data = data.split(',')
 str = ''
 for each in data:
     if each != 'x':
         str += each + ',' + 'x' + ','
 str= str.strip(',')
 print str
Sign up to request clarification or add additional context in comments.

7 Comments

gives: a,x,x,x,b,x,c,x,d,x,e,x
Is there any easier way if we suppose that the file is a csv file using csv module or pandas?
if its csv file better to use csv.DictReader
Sorry i didn't check the x
@M4rtini please check now
|
1
import re
s = open(filename).read()
open(filename, 'w').write(',x,'.join(re.findall(r'[a-wyz]', s)) + ',x\n')

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.