How to strip all whitespace from string

前端 未结 11 1873
暖寄归人
暖寄归人 2020-11-28 18:25

How do I strip all the spaces in a python string? For example, I want a string like strip my spaces to be turned into stripmyspaces, but I cannot s

11条回答
  •  渐次进展
    2020-11-28 19:16

    TL/DR

    This solution was tested using Python 3.6

    To strip all spaces from a string in Python3 you can use the following function:

    def remove_spaces(in_string: str):
        return in_string.translate(str.maketrans({' ': ''})
    

    To remove any whitespace characters (' \t\n\r\x0b\x0c') you can use the following function:

    import string
    def remove_whitespace(in_string: str):
        return in_string.translate(str.maketrans(dict.fromkeys(string.whitespace)))
    

    Explanation

    Python's str.translate method is a built-in class method of str, it takes a table and returns a copy of the string with each character mapped through the passed translation table. Full documentation for str.translate

    To create the translation table str.maketrans is used. This method is another built-in class method of str. Here we use it with only one parameter, in this case a dictionary, where the keys are the characters to be replaced mapped to values with the characters replacement value. It returns a translation table for use with str.translate. Full documentation for str.maketrans

    The string module in python contains some common string operations and constants. string.whitespace is a constant which returns a string containing all ASCII characters that are considered whitespace. This includes the characters space, tab, linefeed, return, formfeed, and vertical tab.Full documentation for string

    In the second function dict.fromkeys is used to create a dictionary where the keys are the characters in the string returned by string.whitespace each with value None. Full documentation for dict.fromkeys

提交回复
热议问题