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 = "example.com#100#2015-10-1" data = url.split("#") print len(data) #3 print data[0] # example.com print data[1] # 100 print data[2] # 2015-10-1 for temp in data: print temp
Выход
3 example.com 100 2015-10-1 example.com 100 2015-10-1