How to remove space in python
Given a string, write a Python program to remove all spaces from it. Show
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() functionPython3
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
Output geek Method 3: Remove spaces from a string using Python regexIn 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
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
Output geek Method 5: Remove spaces from a string using reduce function and conditional statementReduce function iterate over the string and it joins to the element of string to result if it is not white space. Python3
Output: geek Method 6: Remove spaces from a string using lstrip() functionThe lstrip() creates a new string by either deleting whitespace from the string’s “left” side or its leading whitespace. Python3
Output geeksforgeeks.org www. Method 7: Remove spaces from a string using rstrip() functionThe 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
Output www.geeksforgeeks.org Method 8 : Using isspace() methodPython3
How do I remove spaces from a string?strip()—Remove Leading and Trailing Spaces. The str. strip() method removes the leading and trailing whitespace from a string.
How do I remove and replace spaces in Python?The easiest approach to remove all spaces from a string is to use the Python string replace() method. The replace() method replaces the occurrences of the substring passed as first argument (in this case the space ” “) with the second argument (in this case an empty character “”).
|