Python - 使用 split() 函数检测模式

以下示例演示如何使用 Python 中的 split 函数检测模式并拆分字符串。函数 split() 返回字符串中所有单词的列表作为结果。

Split by space

函数 split() 默认为空字符或空格字符作为分隔符。

alphabet = a b c d e f”
tstr = alphabet.split()

for c in tstr:
print c
运行时:

a
b
c
d
e
f
函数 split() 还将字符或模式的最大检测次数作为参数,如下例所示:

alphabet = a b c d e f”
tstr = alphabet.split( ”, 3)

for c in tstr:
print c
Runtime:

a
b
c
d e f

示例 2:提取域名

s = 'exemple.domaine.net'
i = s.split('.', 1)
nom_de_domaine = i[1]
print nom_de_domaine
Runtime:

domaine.net
References:
Python String split() 方法