fsociety fsociety - 28 days ago 5
Python Question

Replace a substring in a string with null in python

I have a string as

a='''123
456
789'''


I want to replace 456 with null, so that the corresponding output is

123
789


The objective is to eliminate the empty line that would be generated as a result of

a=a.replace('456','')

Answer

You are getting empty line after doing replace because '456' is followed by '\n'. In order to remove empty line, replace '456\n' with '' as:

>>> a = a.replace('456\n', '')
>>> print(a)
123
789

where initially a is holding the multiline string mentioned in the question as:

>>> a='''123
    456
    789'''
Comments