Gravity M
Gravity M

Reputation: 1517

Replacing strings line by line

I have a text file testfile.txt, the file contents (input) look like the following:

Msg "how are you"
Msg "Subtraction is", 10-9

Output should look like the following,

Msg("how are you")
Msg("Subtraction is", 10-9)

I opened the file as following,

fileopening = open('testfile.txt', 'r')
fileopening.readline()

for line in fileopening:
   print line.replace(' "', '(')
for line in fileopening:
   print line.replace('"', ')')

But the code above actually changes the previously converted space and quote. How can this be accomplished to make it look like the desired output shown above? I want to take Msg as a single line and wrap the Msg with ( ) and go to the next line.

My new output looked like this:

Msg( "hello"
)

()
Msg( "dfsdkbfsd")

Upvotes: 1

Views: 65

Answers (2)

unutbu
unutbu

Reputation: 879421

Instead of using replace, you could take advantage of the fact that the parentheses are always inserted at the 4th position and the last position:

with open('testfile.txt', 'r') as fileopening:
    next(fileopening)
    for line in fileopening:
        line = line.rstrip()
        print('{}({})'.format(line[:3], line[4:]))

By the way, since you are using Python3, note that print is a function and therefore its argument must be surrounded by parentheses. Using print without parentheses raises SyntaxErrors.

Upvotes: 1

Eliezer
Eliezer

Reputation: 767

One way to solve the problem would be as follows:

with open('testfile.txt', 'r') as f:
    for line in f:
        newline = line.replace(' "', '("')
        newline = newline.replace('\n', ')\n')
        print newline

This wouldn't presume that every line starts with Msg.

Upvotes: 0

Related Questions