Remove spaces from both ends in python

Asked 12 years, 7 months ago

Viewed 206k times

I need to remove whitespaces after the word in the string. Can this be done in one line of code?

Example:

string = "    xyz     "

desired result : "    xyz" 

asked Mar 3, 2010 at 15:36

4

>>> "    xyz     ".rstrip[]
'    xyz'

There is more about rstrip in the documentation.

answered Mar 3, 2010 at 15:37

SilentGhostSilentGhost

293k64 gold badges301 silver badges291 bronze badges

You can use strip[] or split[] to control the spaces values as the following, and here is some test functions:

words = "   test     words    "

# Remove end spaces
def remove_end_spaces[string]:
    return "".join[string.rstrip[]]

# Remove first and  end spaces
def remove_first_end_spaces[string]:
    return "".join[string.rstrip[].lstrip[]]

# Remove all spaces
def remove_all_spaces[string]:
    return "".join[string.split[]]

# Remove all extra spaces
def remove_all_extra_spaces[string]:
    return " ".join[string.split[]]

# Show results
print[f'"{words}"']
print[f'"{remove_end_spaces[words]}"']
print[f'"{remove_first_end_spaces[words]}"']
print[f'"{remove_all_spaces[words]}"']
print[f'"{remove_all_extra_spaces[words]}"']

output:

"   test     words    "

"   test     words"

"test     words"

"testwords"

"test words"

i hope this helpful .

answered Nov 3, 2020 at 14:48

K.AK.A

8808 silver badges18 bronze badges

2

Spaces are also considered as a character inside a string, and sometimes unnecessary spaces in the string cause wrong results.

For example, instead of typing 'Alex', a person typed his name 'Alex  ' [see two spaces at the end of the string], and if we compare them using the '==' operator.

Example:

if 'Alex' == 'Alex  ':
    print ["Hello Alex!"]
else:
    print ["Not found"]

Output:

Not found

The output of the above program will be 'not found', and this way, additional spaces may lead to wrong results. Therefore, such blank spaces should be removed from the string before being used. This is possible by using rstrip[], lstrip[] and strip[] methods in Python. These three functions do the same thing, but there is a slight difference between these three functions.

Function Description
rstrip[] rstrip[] method removes whitespace at the end of a string.
lstrip[] lstrip[] method removes whitespace at the beginning of a string.
strip[] strip[] method removes whitespace at the beginning and end [both sides] of a string.

These three methods do not remove empty spaces between the strings and are usually used where the input is taken from the user.

Example:

name = '  Chris Gayle  '
#remove spaces from left
print [name.lstrip[]]

#remove spaces from right
print [name.rstrip[]]

#remove spaces from both side
print [name.strip[]]

Output:

Chris Gayle  
  Chris Gayle
Chris Gayle

In this article, you'll learn how to trim a string in Python using the .strip[] method.

You'll also see how to use the .lstrip[] and .rstrip[] methods, which are the counterparts to .strip[].

Let's get started!

Python has three built-in methods for trimming leading and trailing whitespace and characters from strings.

  • .strip[]
  • .lstrip[]
  • .rstrip[]

Each method returns a new trimmed string.

How to Remove Leading and Trailing Whitespace from Strings in Python

When the .strip[] method has no argument, it removes any leading and/or trailing whitespace from a string.

So, if you have whitespace at the start and/or end of a word or phrase, .strip[] alone, by default, will remove it.

The following variable greeting has the string "Hello" stored in it. The string has space both to the right and left of it.

greeting = "     Hello!  "

print[greeting,"How are you?"]

#output
#     Hello!   How are you?

To remove both of them, you use the .strip[] method, like so:

greeting = "     Hello!  "

stripped_greeting = greeting.strip[]

print[stripped_greeting,"How are you?"]

#output
#Hello! How are you?

You could have also used the .strip[] method in this way:

greeting = "     Hello!  "

print[greeting.strip[],"How are you?"]

#output
#Hello! How are you?

How to Remove Leading and Trailing Characters from Strings in Python

The .strip[] method takes optional characters passed as arguments.

The characters you add as arguments specify what characters you would like to remove from the start and end of the string.

Below is the general syntax for this case:

str.strip[char]

The characters you specify are enclosed in quotation marks.

So, for example, say you have the following string:

greeting = "Hello World?"

You want to remove "H" and "?", which are at the beginning and at end of the string, respectively.

To remove them, you pass both characters as arguments to strip[].

greeting = "Hello World?"

stripped_greeting = greeting.strip["H?"]

print[stripped_greeting]

#output
#ello World

Notice what happens when you want to remove "W" from "World", which is at the middle and not at the start or end of the string, and you include it as an argument:

greeting = "Hello World?"

stripped_greeting = greeting.strip["HW?"]

print[stripped_greeting]
#ello World

It will not be removed! Only the characters at the start and end of said string get deleted.

That being said, look at the next example.

Say you want to remove the first two and the last two characters of the string:

phrase = "Hello world?"

stripped_phrase = phrase.strip["Hed?"]

print[stripped_phrase]

#output
#llo worl

The first two characters ["He"] and the last two ["d?"] of the string have been removed.

Another thing to note is that the argument does not remove only the first instance of the character specified.

For example, say you have a string with a few periods at the beginning and a few exclamation marks at the end:

phrase = ".....Python !!!"

When you specify as arguments . and !, all instances of both will get removed:

phrase = ".....Python !!!"

stripped_phrase = phrase.strip[".!"]

print[stripped_phrase]

#output
#Python 

How to Remove Only Leading Whitespace and Characters from Strings in Python

To remove only leading whitespace and characters, use .lstrip[].

This is helpful when you want to remove whitespace and characters only from the start of the string.

An example for this would be removing the www. from a domain name.

domain_name = "www.freecodecamp.org www."

stripped_domain = domain_name.lstrip["w."]

print[stripped_domain]

#output
#freecodecamp.org www.

In this example I used the w and . characters both at the start and the end of the string to showcase how .lstrip[] works.

If I'd used .strip[w.] I'd have the following output:

freecodecamp.org 

The same goes for removing whitespace.

Let's take an example from a previous section:

greeting = "     Hello!  "

stripped_greeting = greeting.lstrip[]

print[stripped_greeting,"How are you?" ]

#output
#Hello!   How are you?

Only the whitespace from the start of the string has been removed from the output.

How to Remove only Trailing Whitespace and Characters from Strings in Python

To remove only trailing whitespace and characters, use the .rstrip[] method.

Say you wanted to remove all punctuation only from the end of a string.

You would do the following:

enthusiastic_greeting = "!!! Hello !!!!"

less_enthusiastic_greeting = enthusiastic_greeting.rstrip["!"]

print[less_enthusiastic_greeting]

#output
#!!! Hello 

Same goes for whitespace.

Taking again the example from earlier, this time the whitespace would be removed only from the end of the output:

greeting = "     Hello!  "

stripped_greeting = greeting.rstrip[]

print[stripped_greeting,"How are you?"]

#output
#     Hello! How are you?

Conclusion

And there you have it! You now know the basics of how to trim a string in Python.

To sum up:

  • Use the .strip[] method to remove whitespace and characters from the beginning and the end of a string.
  • Use the .lstrip[] method to remove whitespace and characters only from the beginning of a string.
  • Use the .rstrip[] method to remove whitespace and characters only from the end of a string.

If you want to learn more about Python, check out freeCodeCamp's Python Certification. You'll start learning in an interacitve and beginner-friendly way. You'll also build five projects at the end to put into practice and help reinforce what you learned.

Thanks for reading and happy coding!

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Which method removes whitespace from both ends of a string?

trim[] The trim[] method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters [space, tab, no-break space, etc.]

How do I remove spaces in Python?

The strip[] method is the most commonly accepted method to remove whitespaces in Python. It is a Python built-in function that trims a string by removing all leading and trailing whitespaces.

How do you remove a space at the end of a string?

String result = str. The trim[] method will remove both leading and trailing whitespace from a string and return the result.

What does Isspace [] do in Python?

Python String isspace[] Method The isspace[] method returns True if all the characters in a string are whitespaces, otherwise False.

Chủ Đề