How to Split Line in Python
String in Python can comprise of numeric or alphanumeric text, and it is usually used to store data directories or print messages. The string.split() function is generally used to manipulate the string.
To join two strings in Python, use the concatenation. To split the strings in Python, use the split() method.
How to Split Line in Python
To split the line in Python, use the String split() method. The split() is an inbuilt method that returns a list of lines after breaking the given string by the specified separator. In this tutorial, the line is equal to the string because there is no concept of a line in Python. So you can think of a line as a string.
separator: This is a delimiter argument. It is the separator on which the string splits occur. If the parameter is not provided, then any white space will be considered as a separator.
maxsplit: It is a number, which tells us to split the string into a maximum of the provided number of times. If it is not provided, then there is no limit.
Example of the line split in Python
Define a line(string) and pass that line to the split() function. If you don’t pass any separator, then it will split from the blank space.
line = "Elon musk tweets, GameStonk" data = line.split() print(data)
['Elon', 'musk', 'tweets,', 'GameStonk']
You can see from the output that we have split the line into four elements of a list.
If your input line contains a special symbol like @ or &, you can split the line from that symbol, bypassing that as a separator.
line = "email@example.com" data = line.split("@") print(data)
As you can see that it exactly splits the line at the @ symbol.
Split the lines into a list with a max 1 item
The line split() function takes a maxsplit as a second parameter, which defines how many splits we need to do to the line. Let’s pass the 1 as a second parameter and see how it will split.
line = "Dixon||BajajFinserve||IndiaMART||InfoEdge" data = line.split("||", 1) print(data)
You can see that we have passed 1 as a second argument, and in the output, it only splits at one || symbol. All the others are in the same line in the second element of the list.
Splitting lines from a text file in Python
To read a file in Python, use the with statement with the open() method.
We have a data.txt file, and in that file, we have the following content.
Now, we will read this file using with open() and use the split() method to split the line into the list of items and print that in the console.
with open("data.txt", "r") as ext_file: for line in ext_file: data = line.split('||') print(data)
['Dixon', 'BajajFinserve', 'IndiaMART', 'InfoEdge']
To split a line or string from text or file in Python, use the split() method. You can split the line from whatever character or special symbol you like. That is it for this split line tutorial.