Saurabh Ghorpade
Saurabh Ghorpade

Reputation: 1157

string formatting and concatenation

I am reading the text file which gives me output something like:

o hi! My name is Saurabh.

o I like python.

I have to convert the above output into:

*1 hi! My name is Saurabh

*2 I like python.

Simple string replace (replacing "\no" with "") followed by adding numbers in python gave me :

*1

o hi! My name is Saurabh

*2

o I like python.

Could anybody help me in getting the right output as

*1 hi! My name is Saurabh

*2 I like python.

Upvotes: 0

Views: 120

Answers (3)

SmartElectron
SmartElectron

Reputation: 1441

this is my solution:

import re

f_in=open('data_in.txt', 'r')
f_out=open('data_out.txt', 'w')
ln=1
for line in f_in:
    s = re.sub('^o+','*%-3i' % ln,line)
    f_out.write(s)
    if not line=='\n': ln += 1
f_in.close()
f_out.close()

Upvotes: 0

GodMan
GodMan

Reputation: 2641

IF you read line by line, replacing '\no' is not a solution, because '\n' would not be in the start of your line. You will need to use regex in this case:

import re
f = open('test.txt')
h = open('op.txt','w')
gen = (line.strip() for line in f)

for line in enumerate(gen,1):
    h.write(re.sub('^o','*'+str(line[0]),line[1]) + '\n')
f.close()
h.close()

PS: You might want to check if the line contains nothing, then, dont do anything; else write in the new file

Upvotes: 1

MostafaR
MostafaR

Reputation: 3695

with open('sample.txt', 'r') as fin:
    lines = fin.readlines()

    with open('sample_output.txt', 'w') as fout:
        index = 1
        for line in lines:
            if line[0] == 'o':
                line = '*' + str(index) + line[1:]
                index += 1
            fout.write(line.rstrip() + '\n')

Upvotes: 1

Related Questions