Bootstrap

python中的字符串strip()、split()和re.split()的用法

一、strip()用法

用于移除字符串首尾指定的字符
如果strip()括号里为空,即未指定要删除的字符,默认删除字符串首尾的空格和换行符

输入

str = "   The weather is bright and warm\n"
print("1.", str)
print("2", str.strip())

输出

1.    The weather is bright and warm

2 The weather is bright and warm

二、split()用法

用于指定分隔符对字符串进行切片
如果split()括号内为空,未指定要分割的字符串,默认是按照空格进行分割,返回一个字符串列表

输入

str = "   The weather is bright and warm\n"
print("1.", str)
print("2.", str.split())
print("3.", str.split("e"))

输出

1.    The weather is bright and warm

2. ['The', 'weather', 'is', 'bright', 'and', 'warm']
3. ['   Th', ' w', 'ath', 'r is bright and warm\n']

三、re.split()用法

split不支持同时使用多种字符做分隔符,如果想实现这样的效果,可以用re

输入

import re

str = "   [The weather], is bright and warm!"
print("1.", str)
print("2.", re.split("[\[\],!]", str))

输出

1.    [The weather], is bright and warm!
2. ['   ', 'The weather', '', ' is bright and warm', '']
;