142

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" 
4
  • 20
    @Greg K Yes, because even those who've read the docs might not realize it may be there, seeing as it is a fundamental that they may have tuned out the first few times they read it, and remember it as saying something unrelated. Plus, rstrip in the docs doesn't show up easily in a Google search for this problem (using the criteria 'python strip end of string'). May 15, 2014 at 21:10
  • 7
    real cold @GregK real cold Dec 30, 2015 at 11:26
  • 4
    It also adds to the general unfriendliness which is sadly becoming increasingly characteristic of Stack Overflow. May 17, 2021 at 16:27
  • 1
    Yes it had to be asked. I googled how to do it and I ended up here. I didn't immediately start searching the python library. If all we do is ask google/bing/etc then we stop communicating with each other as people.
    – datagod
    Sep 17, 2021 at 21:30

2 Answers 2

237
>>> "    xyz     ".rstrip()
'    xyz'

There is more about rstrip in the documentation.

18

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 .

2
  • 5
    It's unnecessary to use rstrip() and lstrip() when there's a specific function that does both: strip()
    – autonopy
    Jul 28, 2021 at 19:19
  • 2
    Oh, I see you rejected my edit and then did it yourself. Seems that This edit defaces the post in order to promote a product or service, or is deliberately destructive. wasn't true after all.
    – autonopy
    Jul 28, 2021 at 19:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.