In [10]: sentence = ' hello apple \n \r \t '
In [11]: "".join(sentence.split())
Out[11]: 'helloapple'
In [13]: import re
In [14]: sentence = ' hello apple \n \r \t '
In [15]: pattern = re.compile(r'\s+')
In [16]: sentence = re.sub(pattern, '', sentence)
In [17]: print sentence
helloapple
使用str.translate()
In [78]: sentence = ' hello apple \n\r \n\r'
In [79]: print sentence
hello apple
In [80]: print sentence.translate(None, ' \n\t\r')
helloapple
只去除左边的空白字符
使用str.lstrip()
In [29]: sentence = ' hello apple '
In [30]: sentence.lstrip()
Out[30]: 'hello apple '
In [35]: import re
In [36]: sentence = ' hello apple '
In [37]: sentence = re.sub(r"^\s+", "", sentence, flags=re.UNICODE)
In [39]: sentence
Out[39]: 'hello apple '
只去除右边的空白字符
使用str.rstrip()
In [40]: sentence = ' hello apple '
In [41]: sentence.rstrip()
Out[41]: ' hello apple'
In [43]: import re
In [44]: sentence = ' hello apple '
In [45]: sentence = re.sub(r"\s+$", "", sentence, flags=re.UNICODE)
In [46]: sentence
Out[46]: ' hello apple'
仅去除重复的空白字符
In [66]: import re
In [67]: sentence = ' hello apple '
In [68]: sentence = " ".join(re.split("\s+", sentence, flags=re.UNICODE))
In [69]: sentence
Out[69]: ' hello apple '
综上,str.strip()
会移除字符串中开头与结束(左右两侧)的空白字符,中间部分的空白字符是不会移除的。
strip方法中可自定义要移除的字符,如下面这个示例,移除的为字符串中两侧的逗号
In [85]: ",1,2,3,".strip(",")
Out[85]: '1,2,3'