如何拆分多种分隔符的字符串
字符串对象str.split()
方法只能处理非常简单的情况,而且不支持多个分割符,对分割符周围存在的空格也无能为力,当需要一些更灵活的功能时,应该使用re.spilt()
>>> import re
>>> line = "sdfs sdf, ers; sef|sdf ,sdf ioi"
>>> re.split(r"[,;|\s]\s*", line)
["sdfs", "sdf", "ers", "sef", "sdf", "sdf", "ioi",]
字符串的开头和结尾的文本匹配
检查字符串的开头或着结尾,只要使用str.startswith()
和str.endstartsend()
>>> url = "http://www.python.org"
>>> url.startswith("http:")
True
如果要同时对多个选项做检查,只需要给startswith()
和endswith()
添加多个可能选项的元组就可以,一定要是元组不能是列表,不然会报错
>>> url = "http://www.python.org"
>>> url.startswith(("http:", "https:"))
True
>>> url.startswith(["http:", "https:"])
Traceback (most recent call last):]
File "<stdin>", line 1, in <module>
TypeError: startswith first arg must be str, unicode, or tuple, not list
如何调整字符串文本的格式
使用正则表达式
re.sub(pattern, repl, string, count=0, flags=0)
pattern为表示正则中的模式字符串,
repl为replacement,被替换的内容,repl可以是字符串,也可以是函数。
string为正则表达式匹配的内容。
count由于正则表达式匹配到的结果是多个,使用count来限定替换的个数(顺序为从左向右),默认值为0,替换所有的匹配到的结果。
flags是匹配模式
使用相对位子匹配,第一个括号的内容替换成\1
中的内容
>>> import re
>>> text = "Today is 3/2/2018, tomorrow is 3/3/2018"
>>> text1 = re.sub(r"(\d+)/(\d+)/(\d+)", r"\3-\1-\2", text)
>>> print(text1)
Today is 2018-3-2, tomorrow is 2018-3-3
也可以对其命名
>>> import re
>>> text = "Today is 3/2/2018, tomorrow is 3/3/2018"
>>> text1 = re.sub(r"(?P<month>\d+)/(?P<day>\d+)/(?P<year>\d+)", r"\g<year>-\g<month>-\g<day>", text)
>>> print(text1)
Today is 2018-3-2, tomorrow is 2018-3-3