Python –如何分割字符串
很少有示例向您展示如何在Python中将字符串拆分为列表。
1.按空格分割
默认情况下, split()
将空格用作分隔符。
alphabet = "a b c d e f g"
data = alphabet.split() #split string into a list
for temp in data:
print temp
输出量
a
b
c
d
e
f
g
2.分割+最大分割
仅按前2个空格分割。
alphabet = "a b c d e f g"
data = alphabet.split(" ",2) #maxsplit
for temp in data:
print temp
输出量
a
b
c d e f g
3.用#分割
又一个例子。
url = "mkyong.com#100#2015-10-1"
data = url.split("#")
print len(data) #3
print data[0] # mkyong.com
print data[1] # 100
print data[2] # 2015-10-1
for temp in data:
print temp
输出量
3
mkyong.com
100
2015-10-1
mkyong.com
100
2015-10-1
参考
- Python内置类型
标签: python 拆分
翻译自: https://mkyong.com/python/python-how-to-split-a-string/
还没有评论,来说两句吧...