Removing a substring from a string

Paul Watson pwatson at redlinepy.com
Mon Jan 16 10:38:15 EST 2006


ankit wrote:
> Hi All,
> I want to remove a substring from a string without any additional
> tabs/returns in the output string. Is there any method availaible or
> how can I do it. For the ease, I am giving an example:
> 
> [code]
> mainstr ="""
> ${if:isLeaf}
>   Dont include this isLeaf=True
> ${/if:isLeaf}
> 
> ${if:isStatic}
>   include this isStatic=True
> ${/if:isStatic}
> 
> ${if:!isLeaf}
>    include this isLeaf=False
> ${/if:!isLeaf}
> """
> [/code]
> 
> Now if I want to remove :
> [code]
> substr = ""
> ${if:isLeaf}
>   Dont include this isLeaf=True
> ${/if:isLeaf}
> """
> [/code]
> 
> Expected output is :
> [code]
> ${if:isStatic}
>   include this isStatic=True
> ${/if:isStatic}
> 
> ${if:!isLeaf}
>    include this isLeaf=False
> ${/if:!isLeaf}
> [/code]
> 
> I am using mainstr.replace(substr, "") but it gives me additional
> carriage returns which leads to empty spaces as follows:
> 
> Actual Output:
> [code]
> 
> 
> 
> 
> 
> ${if:isStatic}
>   include this isStatic=True
> ${/if:isStatic}
> 
> ${if:!isLeaf}
>    include this isLeaf=False
> ${/if:!isLeaf}
> [/code]
> 
> Note: See additional newlines before isStatic tag
> 
> 
> Any Suggestions ?

Are you using 'print' to get the output?  Please see the following code 
and note what the 'print' lines which have a comma at the end produce. 
The 'print' statement is not always suitable for producing closely 
controlled output.  Consider constructing the exact string you want and 
using a 'write' method.

$ cat ./jjj.py
#!/usr/bin/python

s = 'now'
print s
print s,
print s

x = s.replace('now', '')
print '%s' % x,
print 'then'
09:34 pwatson [ ruth:/home/pwatson ] 431
$ ./jjj.py
now
now now
  then



More information about the Python-list mailing list