23
loading...
This website collects cookies to deliver better user experience
String.split()
method to convert string to array in Python.split()
method splits the string using a specified delimiter and returns it as a list item. The delimiter can be passed as an argument to the split()
method. If we don’t give any delimiter, the default will be taken as whitespace.split()
method isstring.split(separator, maxsplit)
split()
method takes two parameters, and both are optional.split()
method. Hence it takes whitespace as a separator and splits the string into a list.# Split the string using the default arguments
text= "Welcome to Python Tutorials !!!"
print(text.split())
['Welcome', 'to', 'Python', 'Tutorials', '!!!']
# Split the string using the separator
text= "Orange,Apple,Grapes,WaterMelon,Kiwi"
print(text.split(','))
['Orange', 'Apple', 'Grapes', 'WaterMelon', 'Kiwi']
list()
method, an inbuilt function in Python.# Split the string to array of characters
text1= "ABCDEFGH"
print(list(text1))
text2="A P P L E"
print(list(text2))
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
['A', ' ', 'P', ' ', 'P', ' ', 'L', ' ', 'E']
# Split the string to array of characters using list Comprehension
text1= "ABCDEFGH"
output1= [x for x in text1]
print(output1)
text2="A P P L E"
output2=[x for x in text2]
print(list(text2))
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
['A', ' ', 'P', ' ', 'P', ' ', 'L', ' ', 'E']