Python Split Method

String manipulation plays a major role in software programs. When we declare a string in python, we can’t change it since it is an immutable object. But we can apply some methods and manipulate strings as we need. The split is one such string manipulation method. Python provides split() functionality that helps developers very much. It will help in extracting data at a deeper level. In this post, you can learn what split() method is about and how we can use it. This post is mainly useful for beginners. However, having a basic knowledge of python will help you understand in a better way.

What is a string and how to declare it?

A string is a sequence of characters. A character can be a number, symbol, alphabet, etc. In python, a string is treated as an object. Strings can be declared either with single quotes (' ') or double quotes (" "). Here is the syntax for declaring a string.

StringName = 'String value'

or

StringName = "String value"

This is a small program that shows how strings can be declared.

FirstString = 'Hi'

SecondString = "Hello World"

print("The first string is:", FirstString)

print("The second string is:", SecondString)

The output for this would be,

The first string is: Hi

The second string is: Hello World

Split() method and its parameters

The split() is a built-in method provided by the python that splits a string into several pieces. The number of pieces will be dependent on the given parameters - separator and maxsplit. The split() method returns a list of strings. The syntax for the split() method is as follows.

StringName.split(separator, maxsplit)

separator - It specifies the character that has to be considered as a separator or a delimiter while splitting. By default, whitespace is the separator for the split() method. This is an optional parameter.

maxsplit - It specifies how many splits to perform on the string. By default, the value is -1, which refers to all occurrences. This is an optional parameter. 

How split() works in Python?

Let us take a string and apply the split() method on it without assigning parameters.

#String declaration

SampleString = "Welcome to HKR trainings"

words = SampleString.split()

print(words)

The output for the above is as follows.

['Welcome', 'to', 'HKR', 'trainings']

The split() method scans the string and breaks it into words when it encounters a separator. Since we haven’t specified any separator, the split method took whitespace as a separator by default and split the sentence into words.

Split string with a separator

Let us see how split() works when we specify a separator. Here is a sample program.

#String declaration

OriginalString = "We have blogs on python operators, python generators, etc"

print("The original string is:", OriginalString)

result = OriginalString.split(',')

print("The result after splitting is:", result)

This program will split the string based on the comma as a separator. The output for the above program is as follows.

The original string is: We have blogs on python operators, python generators, etc

The result after splitting is: ['We have posts on python operators', ' python generators', ' etc']

Python Training Certification

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

Split string and assign into variables

We can split a string and assign the results to different variables. This example program shows how to do that.

#String declaration

OriginalString = "Welcome, to, HKR, training"

print("The original string is:", OriginalString)

FirstWord, SecondWord, ThirdWord, FourthWord = OriginalString.split(',')

print("The first word is:", FirstWord)

print("The second word is:", SecondWord)

print("The third word is:", ThirdWord)

print("The fourth word is:", FourthWord)

The output for the above program is as follows.

The original string is: Welcome, to, HKR, training

The first word is: Welcome

The second word is: to

The third word is: HKR

The fourth word is: training

The resultant strings are called tokens.

Split string by character

Python provides a list() method to split a string into a sequence of characters. The list() method accepts the string name as a parameter and returns characters as a result. Let us look at an example.

#String declaration

OriginalString = "Welcome"

print("The resultant characters are:", list(OriginalString))

The output will be as follows.

The resultant characters are: ['W', 'e', 'l', 'c', 'o', 'm', 'e']

How split() works when maxsplit is specified?

The maxsplit will enable the split() method to break the string into a maximum of maxsplit + 1 items. Below is a small program that showcases how maxsplit works.

#String declaration

OriginalString = "Welcome to HKR training"

FirstCase = OriginalString.split(' ', 2)

print("When the string is split by 2 maxsplit:", FirstCase)

SecondCase = OriginalString.split(' ', 5)

print("When the string is split by 5 maxsplit:", SecondCase)

ThirdCase = OriginalString.split(' ', 0)

print("When the string is split by 0 maxsplit:", ThirdCase)

Here is the output for the above program.

When the string is split by 2 maxsplit: ['Welcome', 'to', 'HKR training']

When the string is split by 5 maxsplit: ['Welcome', 'to', 'HKR', 'training']

When the string is split by 0 maxsplit: ['Welcome to HKR training']

In the first case, we have taken '2' as maxsplit. So the input string is broken until it encounters whitespace as a delimiter twice. Hence it returned 3 items as a result.

In the second case, we have taken '5' as maxsplit. Since the input string has only four words, all the words were returned as separate items.

In the third case, we have taken '0' as maxsplit. So the entire input string is returned as a single item.

How do you split a string in python without split method

We can split a string without using the split method, but it takes a lot more work. More work means we hare to write more lines of code to achieve splitting a string. Here is a program that shows how we can split a string without using a split method.

#String declaration

OriginalString = "Welcome to HKR training"

Result = []

pos = -1

last_pos = -1

while ' ' in OriginalString[pos + 1:]:

pos = OriginalString.index(' ', pos + 1)

Result.append(OriginalString[last_pos + 1:pos])

last_pos = pos

Result.append(OriginalString[last_pos + 1:])

print(Result)

The result for the above program will be as follows.

['Welcome', 'to', 'HKR', 'training']

Subscribe to our youtube channel to get new updates..!

What is the difference between strip and split methods in Python?

Both the strip and split methods belong to the string class in python but serve different purposes. The strip method removes specified characters or a substring from the beginning and the end of the input string. Whereas a split method breaks the string based on a delimiter. Let's take an example and see how both the methods work.

#String declaration

OriginalString = "##Hello World##"

print("The original string is:", OriginalString)

#Applying the strip method

StrippedString = OriginalString.strip('#')

print("The string after stripping is:", StrippedString)

#Applying the split method

SplittedString = OriginalString.split(' ')

print("The string after splitting is: ", SplittedString)

The output for the above program is as follows.

The original string is: ##Hello World##

The string after stripping is: Hello World

The string after splitting is: ['##Hello', 'World##']

Advantages of the split method

  • Below are the advantages of using the split method.
  • We can decode encrypted strings easily.
  • It is easy to analyze and deduct conclusions.
  • We can break a huge string into multiple chunks.
  • The split method returns a list of words.

Python Training Certification

Weekday / Weekend Batches

Useful tips for applying split() method

Here are some tips to keep in mind while working with the split() method. 

  • The split() method only works on strings.
  • When you specify maxsplit in the split() method, you will get maxsplit + 1 items as a result.
  • If you do not specify any separator in the method and give only single quotes (like split('')), python will throw an error. We should at least give whitespace as a separator or just
  • leave it empty.
  • The split() method works best to read your CSV files.
Conclusion

The split() method is used to extract a specific value or from an input string. It is the most commonly used string manipulation method. In this post, you have learned about all the possible ways a split() method can be applied to strings for manipulation. You have also gone through all the cases with examples. Now you are one step close to becoming a python expert and take the python certification course so elevate your tech skills.. 

Categories

SAP

Request for more information

Webinar

Register free live webinar on Linux Shell Scripting

30th October | 07:00 pm

0 Registered

John
John
Cloud Technologies & Cyber Security
John is a Post Graduate in Computer Science from Andhra University .She is currently working as an IT developer at hkr trainings.com. And he has great experience includes both IT development and operational roles. Connect with him on LinkedIn and Twitter. Thank you

WhatsApp
To Top