Skip to content Skip to sidebar Skip to footer

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 a

Solution 1:

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.


Solution 2:

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.


Post a Comment for "Replacing Strings Line By Line"