149

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'). Commented May 15, 2014 at 21:10
  • 7
    real cold @GregK real cold Commented Dec 30, 2015 at 11:26
  • 4
    It also adds to the general unfriendliness which is sadly becoming increasingly characteristic of Stack Overflow. Commented 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. Commented Sep 17, 2021 at 21:30

2 Answers 2

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

There is more about rstrip in the documentation.

Sign up to request clarification or add additional context in comments.

Comments

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 Comments

It's unnecessary to use rstrip() and lstrip() when there's a specific function that does both: strip()
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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.