Removal of whitespaces

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sashi2keng
    New Member
    • Feb 2010
    • 4

    Removal of whitespaces

    Hi,
    I have a content like this in string
    Code:
         sa
         sp
         sq
    How can I remove the whitespaces so that it becomes:
    Code:
    sa
    sp
    sq
    Using lstrip only trims the whitespace for the first one like this:
    Code:
    sa
        sp
        sq
    Please suggest me a solution

    Thanks,
    Sashi.
    Last edited by bvdet; Mar 12 '10, 11:27 AM. Reason: Add code tags
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    A general solution:
    Code:
    s = '''     sa
         sp
         sq'''
    
    print "\n".join([item.strip() for item in s.split("\n")])
    If you know how many spaces you need to remove:
    Code:
    print s.replace("\n     ", "\n").strip()
    Using the re module:
    Code:
    import re
    
    print re.sub(r"\n *", "\n", s).lstrip()

    Comment

    • sashi2keng
      New Member
      • Feb 2010
      • 4

      #3
      Thanks a lot! The first solution worked.

      Regards,
      Sashi

      Comment

      Working...