Is there a simple way to remove multiple spaces in a string?

后端 未结 29 1434
星月不相逢
星月不相逢 2020-11-22 08:17

Suppose this string:

The   fox jumped   over    the log.

Turning into:



        
相关标签:
29条回答
  • 2020-11-22 09:10

    I've got a simple method without splitting:

    a = "Lorem   Ipsum Darum     Diesrum!"
    while True:
        count = a.find("  ")
        if count > 0:
            a = a.replace("  ", " ")
            count = a.find("  ")
            continue
        else:
            break
    
    print(a)
    
    0 讨论(0)
  • 2020-11-22 09:11
    >>> import re
    >>> re.sub(' +', ' ', 'The     quick brown    fox')
    'The quick brown fox'
    
    0 讨论(0)
  • 2020-11-22 09:11

    One line of code to remove all extra spaces before, after, and within a sentence:

    sentence = "  The   fox jumped   over    the log.  "
    sentence = ' '.join(filter(None,sentence.split(' ')))
    

    Explanation:

    1. Split the entire string into a list.
    2. Filter empty elements from the list.
    3. Rejoin the remaining elements* with a single space

    *The remaining elements should be words or words with punctuations, etc. I did not test this extensively, but this should be a good starting point. All the best!

    0 讨论(0)
  • 2020-11-22 09:12

    foo is your string:

    " ".join(foo.split())
    

    Be warned though this removes "all whitespace characters (space, tab, newline, return, formfeed)" (thanks to hhsaffar, see comments). I.e., "this is \t a test\n" will effectively end up as "this is a test".

    0 讨论(0)
  • 2020-11-22 09:14

    This also seems to work:

    while "  " in s:
        s = s.replace("  ", " ")
    

    Where the variable s represents your string.

    0 讨论(0)
  • 2020-11-22 09:16

    If it's whitespace you're dealing with, splitting on None will not include an empty string in the returned value.

    5.6.1. String Methods, str.split()

    0 讨论(0)
提交回复
热议问题