添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
仗义的手术刀  ·  Looking for a ...·  50 分钟前    · 
失落的鸡蛋面  ·  2. 词法分析 — Python ...·  2 小时前    · 
暴走的电池  ·  python ...·  2 小时前    · 
面冷心慈的人字拖  ·  Issue 28637: Python ...·  7 小时前    · 
酷酷的足球  ·  GitHub - ...·  2 月前    · 
呐喊的便当  ·  通过 iTextSharp 实现PDF ...·  5 月前    · 
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