Python | Remove unwanted spaces from string

Python | Remove unwanted spaces from string

To remove unwanted spaces from a string in Python, you can use several approaches depending on the specific requirements:

  1. Remove Leading and Trailing Spaces:

    s = " Hello, World! " s = s.strip() print(s) # Outputs: "Hello, World!" 
  2. Remove All Spaces: If you want to remove all spaces from a string:

    s = "Hello, World!" s = s.replace(" ", "") print(s) # Outputs: "Hello,World!" 
  3. Remove Multiple Consecutive Spaces: To replace multiple consecutive spaces with a single space:

    import re s = "Hello, World!" s = re.sub(' +', ' ', s) print(s) # Outputs: "Hello, World!" 
  4. Remove Leading, Trailing, and Multiple Consecutive Spaces: Combining the strip() method and the regex approach, you can handle all types of unwanted spaces:

    import re s = " Hello, World! " s = re.sub(' +', ' ', s.strip()) print(s) # Outputs: "Hello, World!" 

Choose the method that suits your specific needs. If you're dealing with a variety of whitespace characters (like tabs and newlines), you can adjust the regex patterns accordingly.


More Tags

median paramiko casting opera httppostedfilebase string-interpolation telephony sign print-css pytube

More Programming Guides

Other Guides

More Programming Examples