How to remove space in python output

Python provides various ways to remove white-spaces from a String. This article will focus of some of the efficient techniques to remove spaces from a String.

Either of the following techniques can be used to get rid of the spaces from a string:

  • By using strip[] method
  • By using replace[] method
  • By using join[]with split[] method
  • By using translate[] method
  • By using Regular Expressions

Method 1: By using strip[] method

The split[] function basically removes the leading and the trailing spaces of the string.

Key points:

  • strip[]: This function removes the leading and the trailing spaces from an array including the tabs[\t].
  • lstrip[]: This function removes spaces from the left end of the string.
  • rstrip[]: This function removes spaces from the right end of the string.

Example:

string = '   Safa Mulani is a student of Engineering Discipline.    '

print[f'String =\'{string}\'']

print[f'After Removing Leading Whitespaces String =\'{string.lstrip[]}\'']

print[f'After Removing Trailing Whitespaces String =\'{string.rstrip[]}\'']

print[f'After Trimming Whitespaces String =\'{string.strip[]}\'']

Output:

Output-strip[] Function

Method 2: By using replace[] method

This function removes all the spaces from the string, removes spaces between words too.

Example:

def remove[string_input]: 
    return string_input.replace[" ", ""] 
      

string_input = ' S a f a '
print[remove[string_input]] 

Output:

Safa

Method 3: By using join[] and split[] method

The join[] and split[] function work in accordance altogether. Firstly, the split[] method returns a list of words in the entire string using a delimiter. Then we need to use the join[] method to concatenate them.

Example:

def remove[string_input]: 
    return "".join[string_input.split[]] 
      
# Driver Program 
string_input= ' S a f a '
print[remove[string_input]]

Output:

Safa

Method 4: By using translate[] method

translate[] Function

In the above example, the translate[] function removes all of the white-spaces from the string and results in a compact string as output.

Method 5: By using Regular Expressions

The re.sub[] function is used to remove the white-spaces from a string.

import re

string = '  Engineering and Medical are altogether different disciplines. \t\n Agreed!!  '

print['String after removal of all the spaces using Regular Expressions:\n', re.sub[r"\s+", "", string], sep=''] 


print['String after removal of leading spaces using Regular Expressions:\n', re.sub[r"^\s+", "", string], sep='']  # ^ matches start

print['String after removal of trailing spaces using Regular Expressions:\n', re.sub[r"\s+$", "", string], sep='']  # $ matches end

print['String after removal of leading and trailing spaces using Regular Expressions:\n', re.sub[r"^\s+|\s+$", "", string], sep='']  # | for OR condition

Output:

Output-Removal Of Spaces Using RegEx

Conclusion

Thus, in this article we have implemented various techniques to remove white-spaces from an input string in Python.

References

  • Python Remove Spaces from String
  • Python string functions Documentation

Given a string, write a Python program to remove all spaces from it.

Examples:

Input  : g e e k
Output : geek

Input  : Hello World
Output : HelloWorld

There are various approaches to removing whitespaces in a string. The first one is the Naive approach, which has been discussed in this article. But here we will discuss all the approaches which are specific to Python.

Method 1: Remove spaces from a string using replace[] function

Python3

def remove[string]:

    return string.replace[" ", ""]

string = ' g e e k '

print[remove[string]]

Output

geek

 Method 2: Remove spaces from a string using split[] and join[] 

First, we use the split[] function to return a list of the words in the string, using sep as the delimiter Python string. Then, we use join[] to concatenate the iterable. 

Python3

def remove[string]:

    return "".join[string.split[]]

string = ' g e e k '

print[remove[string]]

Output

geek

 Method 3: Remove spaces from a string using Python regex 

In order to find a string or group of strings, a Regular Expression [RegEx] is a unique string of characters. It may compare a text to a pattern to determine whether it is present or absent. It can also divide a pattern into one or more sub-patterns.

Python3

import re

def remove[string]:

    pattern = re.compile[r'\s+']

    return re.sub[pattern, '', string]

string = ' g e e k '

print[remove[string]]

Output

geek

 Method 4: Remove spaces from a string using translate[] 

translate[] returns a string that is a modified string of givens string according to given translation mappings.

Python3

import string

def remove[string]:

    return string.translate[None, ' \n\t\r']

string = ' g e e k '

print[remove[string]]

Output

geek

Method 5: Remove spaces from a string using reduce function and conditional statement

Reduce function iterate over the string and it joins to the element of string to result if it is not white space. 

Python3

from functools import reduce

def remove[string]:

    return reduce[lambda x, y: [x+y] if [y != " "] else x, string, ""];

string = ' g e e k '

print[remove[string]]

Output:

geek

Method 6: Remove spaces from a string using lstrip[] function

The lstrip[] creates a new string by either deleting whitespace from the string’s “left” side or its leading whitespace.

Python3

string = "www.geeksforgeeks.org www."

string_new = string.lstrip["w."]

print[string_new]

Output

geeksforgeeks.org www.

Method 7: Remove spaces from a string using rstrip[] function

The rstrip[] creates a new string by removing the trailing whitespace. Eliminating the white spaces from the string’s “right” side makes it simpler to recall.

Python3

string = "www.geeksforgeeks.org www."

string_new = string.rstrip["w."]

print[string_new]

Output

www.geeksforgeeks.org 

Method 8 : Using isspace[] method

Python3

def remove[string]:

    ns=""

    for i in string:

        if[not i.isspace[]]:

            ns+=i

    return ns   

string = ' g e e k '

print[remove[string]]


How do you remove text after space in Python?

Use str. split[] to remove everything after a character in a string.

Chủ Đề