Convert string to list in Python | Python string split() method
String
split() Method
The split() method splits a string into a list.
You can specify the separator, default separator is any
whitespace.
When maxsplit is specified, the list will contain the
specified number of elements plus one.
Syntax
string.split(separator, maxsplit)
Parameter Values
Parameter |
Description |
separator |
Optional. Specifies the separator to use when splitting the string. By
default any whitespace is a separator |
maxsplit |
Optional. Specifies how many splits to do. Default value is -1, which
is "all occurrences" |
Example
1
Split a string into a list where each word is a list item:
a = "welcome to the jungle"
x = a.split()
print(x)
Output: [‘welcome’, ‘to’, ‘the’, ‘jungle’]
Example
Split
the st 2ring, using comma, followed by a space, as a separator
a = "hello, my name is Peter, I am a computer teacher"
x = a.split(", ")
print(x)
Output: [‘hello’, ‘my name is Manoj’, ‘I am a computer teacher’]
Example
3
Use
a hash character as a separator
a = "apple#banana#cherry#orange"
x = a.split("#")
print(x)
Output: [‘apple’, ‘banana’, ‘cherry’, ‘orange’]
Example
4
Split
the string into a list with max 2 items
a = "apple#banana#cherry#orange"
x = a.split("#", 1)
print(x)
Output: [‘apple’, ‘banana#cherry’#orange’]
Example
5
Split a string into a list where each word is a list item given by
the user input:
a = input(“Enter value: “)
x = a.split();
print(x)
Output: Enter value: My name is Manoj
[‘My’, ‘name’,
‘is’, ‘Manoj’]
Example
6
Split a string into a list where each word is a list item given by
the user Multiple input like enter “4” inputs:
a = []
for x in range(4);
x=input(“Enter value”)
a.append(x)
print(a)
Output: Enter value: apple
Enter value: orange
Enter value: banana
Enter value: grapes
[‘apple’, ‘orange’,
‘banana’, ‘grapes’]
Post a Comment