dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: Remove Whitespaces from the string

  1. #1
    Join Date
    Apr 2019
    Posts
    2

    Remove Whitespaces from the string

    How Can I remove the whitespaces from the string “aaa bbb ccc ddd eee”?

  2. #2
    Join Date
    Apr 2019
    Posts
    2

    Re: Remove Whitespaces from the string

    I can think of two ways to do this.

    Using join-
    >>> s='aaa bbb ccc ddd eee'
    >>> s1=''.join(s.split())
    >>> s1
    ‘aaabbbcccdddeee’

    Using a list comprehension-
    >>> s='aaa bbb ccc ddd eee'
    >>> s1=str(''.join(([i for i in s if i!=' '])))
    >>> s1
    ‘aaabbbcccdddeee’

  3. #3
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,762

    Re: Remove Whitespaces from the string

    If you want to specifically remove spaces from a string s, then the simplest option would be:
    Code:
    s.replace(' ', '')
    If you want to remove whitespace in general, then aakashdata's first example would work, but a variation of aakashdata's second example to use a generator instead of a list comprehension and to check for whitespace instead of just a space might be better:
    Code:
    import string
    ''.join(c for c in s if c not in string.whitespace)
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)