How do I remove whitespace from the end of a string in Python?

后端 未结 2 658
孤城傲影
孤城傲影 2020-12-04 17:36

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 :         


        
相关标签:
2条回答
  • 2020-12-04 17:50

    you can use strip() or split() to control the spaces values as the following:

    words = "   first  second   "
    
    # 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())
    
    print(words)
    print(remove_end_spaces(words))
    print(remove_first_end_spaces(words))
    print(remove_all_spaces(words))
    

    i hope this helpful .

    0 讨论(0)
  • 2020-12-04 17:59
    >>> "    xyz     ".rstrip()
    '    xyz'
    

    more about rstrip in docs

    0 讨论(0)
提交回复
热议问题