添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
爱运动的铁链  ·  multiprocessing.shared ...·  2 天前    · 
旅途中的鼠标垫  ·  7125messi的博客·  2 天前    · 
憨厚的大脸猫  ·  python ...·  2 天前    · 
霸气的花卷  ·  python list 错位相减 ...·  2 天前    · 
不羁的剪刀  ·  linuxoffice命令行 • ...·  4 月前    · 
独立的手链  ·  count | StarRocks·  8 月前    · 
逆袭的葡萄酒  ·  VS2015 ...·  1 年前    · 
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'
strip does a rstrip and lstrip (removes leading and trailing spaces, tabs, returns and form 
feeds, but it does not remove them in the middle of the string).

remove-all-whitespace-in-a-string-in-python

string.html

whitespace.html