Python delete spaces in first and end

Remove whitespace from the start and end of a string in Python

In Python, there are several methods for eliminating spaces from a string. The goal of this lesson is to give a brief illustration of each technique we might use to eliminate whitespace from a string.

Читайте также:  Как растягивать кнопку css

Python function to eliminate white space from a string

We cannot alter the value of a Python String since it is immutable. Any function that alters a string value produces a brand-new string, which must be explicitly assigned to the original string. The string value won’t change in any other case.

Let’s examine several functions for removing white spaces.

1. strip() to eliminate leading and ending whitespaces from a string in Python

Leading and ending whitespaces will be eliminated using the Python String strip() method.

Python Code will be:

a=" Amandeep Singh " print(a.strip())

2. replace() to eliminate all whitespaces

To eliminate all whitespace from the string, use replace() . The whitespace in between words will also be eliminated by this function.

Python Code will be:

a=" Amandeep Singh " print(a.replace(" ", ""))

3. join() with split() to remove duplicate whitespaces and \n

Use the join() method along with the string split() function to eliminate any duplicate whitespace and newline characters.

Python Code will be:

a=" Amandeep Singh \n Codespeedy" print(a) print("Use join() with split()") print( " ".join(a.split()))

The output will be:

Amandeep Singh Codespeedy Use join() with split() Amandeep Singh Codespeedy

4. Using Regex to remove whitespaces

Additionally, we may match whitespace with a regular expression and eliminate it using the re.sub() method.

Python Code will be:

import re a=" Amandeep Singh Codespeedy" print(re.sub(r"^\s+|\s+$", "", a), sep='') # | for OR condition

The output will be:

Amandeep Singh Codespeedy

So these are some ways through which you can remove whitespace from the start and end of a string in Python. I hope you like this article.

Источник

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

Источник

Remove Spaces from String in Python

Remove Spaces from String in Python

We can’t change the value of a Python String because it’s immutable. Any function that manipulates string values returns a new string, which must be explicitly assigned to the string otherwise the string value will remain unchanged. In this article, we’ll learn how to remove spaces from a string in Python using several methods. So let’s get started!

What are Strings in Python?

Strings are arrays of bytes in Python that represent Unicode characters. However, because Python lacks a character data type, a single character is merely a one-length string. One can use Square brackets can be used to access the string’s elements.

How to create a string in Python?

Strings can be made by enclosing characters within single or double-quotes. In Python, triple quotes can be used to represent multiline strings and docstrings.

For example:

# creating strings in Python my_string = "Hello World" print(my_string) # triple quotes string extending to multiple lines my_string = """Hello, let's learn to code in Python""" print(my_string)
Hello World Hello,let's learn to code in Python

How to Remove Spaces from a String in Python?

There are 4 methods for removing whitespace from a string. But, in this section, we’ll go through all of the Python-specific ways.

1) Using replace() method

All whitespaces are replaced with no space(«») using the replace() method.

For example:

def remove(string): return string.replace(" ", "") string = ' a p p l e '
print(remove(string))

2) Using split() and join()

First, using sep as the delimiter string, we utilize the split() function to return a list of the words in the string. The iterable is then concatenated using join().

For example:

def remove(string): return "".join(string.split()) string = ' a p p l e ' 
print(remove(string))

3) Using python regex

For example:

import re def remove(string): pattern = re.compile(r'\s+') return re.sub(pattern, '', string) string = ' a p p l e ' print(remove(string))

4) Using translate()

For example:

import string def remove(string): return string.translate(None, ' \n\t\r') string = ' a p p l e ' print(remove(string))

Remove Spaces from the Beginning of a String in Python

The following method will only remove spaces from the beginning of the string in python.

For example:

my_string = " Rose" print(my_string.lstrip())

Remove Trailing Spaces from a String in Python

Using this method, only the trailing spaces can be removed in a string.

For example:

my_string = " Rose " print(my_string.rstrip())

The string strip() method can be used to eliminate spaces from both the beginning and end of a string. Learn more about rstrip in python here.

For example:

my_string = " Rose " print(my_string.strip()) print(len(my_string.strip()))

Because spaces at the beginning and end of the string have been eliminated, the strip() method returns a string with just 5 characters.

Conclusion

In summary, we learnt different methods to remove spaces within a string and also methods to remove spaces from the beginning and end of a string. You now have a sufficient number of options for replacing or removing white spaces from Python strings. Simply choose the one that appeals to you and is appropriate for the situation at hand.

FavTutor — 24×7 Live Coding Help from Expert Tutors!

About The Author

Adrita Das

I am Adrita Das, a Biomedical Engineering student and technical content writer with a background in Computer Science. I am pursuing this goal through a career in life science research, augmented with computational techniques. I am passionate about technology and it gives immense happiness to share my knowledge through the content I make.

Источник

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