How to remove white spaces from a string in Python?

前端 未结 6 1790
小蘑菇
小蘑菇 2020-12-10 00:27

I need to remove spaces from a string in python. For example.

str1 = \"TN 81 NZ 0025\"

str1sp = nospace(srt1)

print(str1sp)

>>>TN81NZ0025
         


        
相关标签:
6条回答
  • 2020-12-10 00:36

    Use str.replace:

    >>> s = "TN 81 NZ 0025"
    >>> s.replace(" ", "")
    'TN81NZ0025'
    

    To remove all types of white-space characters use str.translate:

    >>> from string import whitespace
    >>> s = "TN 81   NZ\t\t0025\nfoo"
    # Python 2
    >>> s.translate(None, whitespace)
    'TN81NZ0025foo'
    # Python 3
    >>> s.translate(dict.fromkeys(map(ord, whitespace)))
    'TN81NZ0025foo'
    
    0 讨论(0)
  • 2020-12-10 00:44

    Mind that in python strings are immutable and string replace function returns a string with the replaced value. If you are not executing the statement at the shell but inside a file,

     new_str = old_str.replace(" ","" )
    

    This will replace all the white spaces in the string. If you want to replace only the first n white spaces,

    new_str = old_str.replace(" ","", n)
    

    where n is a number.

    0 讨论(0)
  • 2020-12-10 00:44

    Try this:

    s = "TN 81 NZ 0025"
    s = ''.join(s.split())
    
    0 讨论(0)
  • 2020-12-10 00:45

    You can replace every spaces by the string.replace() function:

    >>> "TN 81 NZ 0025".replace(" ", "")
    'TN81NZ0025'
    

    Or every whitespaces caracthers (included \t and \n) with a regex:

    >>> re.sub(r'\s+', '', "TN 81 NZ 0025")
    'TN81NZ0025'
    >>> re.sub(r'\s+', '', "TN 81 NZ\t0025")  # Note the \t character here
    'TN81NZ0025'
    
    0 讨论(0)
  • 2020-12-10 00:45

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

    string = "  TN 81 NZ 0025  "
    string = ''.join(filter(None,string.split(' ')))
    

    Explanation:

    1. Split entire string into list.
    2. Filter empty elements from list.
    3. Rejoin remaining elements with nothing
    0 讨论(0)
  • 2020-12-10 00:54

    You can replace multiple spaces into a desired pattern by using following ways. Here your pattern is blank string.

    import re
    pattern = ""
    re.sub(r"\s+", pattern, your_string)
    

    or

    import re
    pattern = ""
    re.sub(r" +", "", your_string)
    
    0 讨论(0)
提交回复
热议问题