Python str delete spaces

Python Remove Spaces from String

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:

Method 1: By using strip() method

The split() function basically removes the leading and the trailing spaces of the string.

  • 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.
string = ' Safa Mulani is a student of Engineering Discipline. ' print(f'String =\'\'') print(f'After Removing Leading Whitespaces String =\'\'') print(f'After Removing Trailing Whitespaces String =\'\'') print(f'After Trimming Whitespaces String =\'\'')

Output Strip Function

Method 2: By using replace() method

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

def remove(string_input): return string_input.replace(" ", "") string_input = ' S a f a ' print(remove(string_input))

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.

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

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.

Читайте также:  Get cookies with javascript

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 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

Источник

How to Remove Spaces from String in Python

To remove spaces from a string in Python, use the str.replace() method.

This method takes two arguments:

  • The first argument is the string to be replaced.
  • The second argument is the string that replaces the string.
string = "This is a test" nospaces = string.replace(" ", "") print(nospaces)

To learn other useful string methods in Python, feel free to check this article.

In this guide, we take a look at other common situations related to removing spaces from a string.

Howt to Remove White Spaces in Python String

In Python, a string is an immutable type. This means it cannot be directly modified. This means any method that manipulates strings actually creates a new string.

In Python, there are many ways you can replace blank spaces:

Let’s go through each of these options and when you should use them.

1. str.strip()—Remove Leading and Trailing Spaces

The str.strip() method removes the leading and trailing whitespace from a string.

string = " This is a test " modified = string.strip() print(modified)

2. str.replace()—Remove All White Spaces

To wipe out all the white spaces from a string, you can use the str.replace() method.

This method takes two mandatory arguments:

  1. The target strings you want to get rid of.
  2. The string that replaces all the target strings.

In other words, to remove the white spaces, replace each white space with an empty string.

string = "This is a test" modified = string.replace(" ", "") print(modified)

3. str.join() and str.split()—Remove Duplicate White Spaces

To get rid of tabs, newlines, or any other duplicate whitespaces use str.join() method with str.split().

  • The str.split() method splits the string into a list of words without spaces.
  • The str.join() takes a list of words and joins them using the str as a separator.

For example, let’s remove the duplicate white spaces but leave single white spaces:

before = "This \t is a \n test \n\n \t let's modify this" after = " ".join(before.split()) print(before) print(after)
This is a test let's modify this This is a test let's modify this

4. str.translate()—Remove Tabs, Newlines, and Other White Spaces

To get rid of all the white spaces, tabs, newlines, you can use the str.translate() method with str.maketrans() method.

The str.translate() method replaces strings according to a translation table created by str.maketrans() method. In short, the str.maketrans() method works such that it takes three arguments:

  1. A string to be replaced.
  2. A string that specifies the characters to be replaced in the first argument.
  3. A list of characters to be removed from the original string. To remove white spaces, use string.whitespaces, which is a list of the types of blank spaces.
import string before = "This \t is a \n test \n\n \t let's modify this" after = before.translate(str.maketrans("", "", string.whitespace)) print(before) print(after)
Thisisatestlet'smodifythis

5. re.sub()—Replace White Spaces with Empty Strings

RegEx or Regular Expression is like a Ctrl+F on steroids.

You can use it to match patterns in a string. You can for example use regex to find phone numbers or email addresses from a text document.

I am not going to go into more details about regex, but here is a great article you can check.

To use Regular Expressions in Python to remove white spaces from a string:

  1. Import the regex module, re, to your project.
  2. Define a regex pattern that matches white spaces.
  3. Substitute each white space with a blank space using re.sub() method.
import re string = "This is a test" # Regular expression that matches each white space whitespace = r"\s+" # Replace all mathces with an empty string nospaces = re.sub(whitespace, "", string) print(nospaces)

Conclusion

Today you learned five ways to remove white spaces and duplicate white spaces from Python strings in different situations. Feel free to use the one that best fits your needs!

Thanks for reading. I hope you found an answer to your question.

Further Reading

3 thoughts on “How to Remove Spaces from String in Python”

Франчайзинговое соглашение – это, по сути,
юридическая документация между франчайзером
и вами (франчайзи). На самом деле не существует
основного типа франчайзи

При выборе яхты важно принять во чуткость чуть-чуть принципов.
Вначале, что поделаешь сделать свой выбор кот величиной яхты и еще обличьем движков, что придвинутся для
ваших потребностей. Во-других,
устремите внимание сверху бюджет, поскольку стоимость товаров сверху яхты смогут варьироваться через пары тыщ ут
пары миллионов долларов. Третьим принципом является поиск лично пригодной яхты.
Некоторые штаты могут принять яхту прямо у производителя, часть ну люд
покупать язык дилера или аукциона.
Сосредоточьте внимание, яко некоторые яхты смогут являться подвергнуты специальным лимитированиями и
еще запретам, так что перед покупкой вам стоит
расследовать наличность классических документов.

At the beginning, I was still puzzled. Since I read your article, I have been very impressed. It has provided a lot of innovative ideas for my thesis related to gate.io. Thank u. But I still have some doubts, can you help me? Thanks.

Источник

Remove Space in Python – (strip Leading, Trailing, Duplicate spaces in string)

Remove space in python string / strip space in python string : In this Tutorial we will learn how to remove or strip leading , trailing and duplicate spaces in python with lstrip() , rstrip() and strip() Function with an example for each . lstrip() and rstrip() function trims the left and right space respectively. strip() function trims all the white space.

  • Remove (strip) space at the start of the string in Python – trim leading space
  • Remove (strip) space at the end of the string in Python – trim trailing space
  • Remove (strip) white spaces from start and end of the string – trim space.
  • Remove all the spaces in python
  • Remove Duplicate Spaces in Python
  • Trim space in python using regular expressions.

Let’s see the example on how to Remove space in python string / strip space in python string one by one.

Remove Space at the start of the string in Python (Strip leading space in python):

## Remove the Starting Spaces in Python string1=" This is Test String to strip leading space" print (string1) print (string1.lstrip())

lstrip() function in the above example strips the leading space so the output will be

‘ This is Test String to strip leading space’

‘This is Test String to strip leading space’

Remove Space at the end of the string in Python (Strip trailing space in python):

## Remove the Trailing or End Spaces in Python string2="This is Test String to strip trailing space " print (string2) print (string2.rstrip())

rstrip() function in the above example strips the trailing space so the output will be

‘This is Test String to strip trailing space ‘

‘This is Test String to strip trailing space’

Remove Space at the Start and end of the string in Python (Strip trailing and trailing space in python):

## Remove the whiteSpaces from Beginning and end of the string in Python string3=" This is Test String to strip leading and trailing space " print (string3) print (string3.strip())

strip() function in the above example strips, both leading and trailing space so the output will be

‘ This is Test String to strip leading and trailing space ‘

‘This is Test String to test leading and trailing space’

Remove or strip all the spaces in python:

## Remove all the spaces in python string4=" This is Test String to test all the spaces " print (string4) print (string4.replace(" ", ""))

The above example removes all the spaces in python. So the output will be

‘ This is Test String to test all the spaces ‘

‘ThisisTestStringtotestallthespaces’

Remove or strip the duplicated space in python:

# Remove the duplicated space in python import re string4=" This is Test String to test duplicate spaces " print (string4) print (re.sub(' +', ' ',string4))
  • We will be using regular expression to remove the unnecessary duplicate spaces in python.
  • sub() function: re.sub() function takes the string4 argument and replaces one or more space with single space as shown above so the output will be.

‘ This is Test String to test duplicate spaces ‘

‘ This is Test String to test duplicate spaces ‘

Using Regular Expression to trim spaces:

re.sub() function takes the string1 argument and apply regular expression to trim the white spaces as shown below

string1 = " This is to test space " print('Remove all space:',re.sub(r"\s+", "", string1), sep='') # trims all white spaces print('Remove leading space:', re.sub(r"^\s+", "", string1), sep='') # trims left space print('Remove trailing spaces:', re.sub(r"\s+$", "", string1), sep='') # trims right space print('Remove leading and trailing spaces:', re.sub(r"^\s+|\s+$", "", string1), sep='') # trims both

so the resultant output will be


Remove all space:’Thisistotestspace’
Remove leading space:’This is to test space ‘
Remove trailing spaces:’ This is to test space’
Remove leading and trailing spaces:’This is to test space’

Author

With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark. View all posts

Источник

Оцените статью