How to split and join a string in Python

Splitting a string in Python

 

 

Splitting a string refers to dividing the whole string in sub strings.We can split a string in python using split() method.Split() method is used to split a string into an array of substrings. The split() method takes a pattern and divides a string into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.

Lets take an example to have a better understanding:

# Splitting a string in python
# Split the string into list of strings
Input: I am Samuel Malhotra 
Output:['I','am','Samuel','Malhotra']

In Python, we can use the function split() to split a string . The split() method in Python split a string into a list of strings after breaking the given string by the specified separator as in the above example.The split method () splits the whole string into substrings i.e. words.

 

Joining substrings into a string

 

Joining substrings to a string refers to concatenate two or more strings to a single string.Python String join() method is a string method which returns a string in which the elements of the sequence have been joined by using appropriate separator.The seperator could be any specific character or space .Join() is an predefined  string function used in python to join elements of the sequence separated by a string separator to form a single string. This function joins elements of a sequence and makes it a string.

The sequence may belong to Tuple,Dictionary,Lists and any ordered array.

Lets take an example to have a better understanding:

# Joining a string in python
# Join the elements of the sequence to a string
Tuple1 = ( "I" , "am" , "Samuel" , "Malhotra" )
Str=" ".join(Tuple1)
print(Str)

The output produced by the code will be :

I am Samuel Malhotra

 

In this way ,we use both split() method as well as join() method in python to split and join strings ,respectively.We could use both methods in the same program by using different different delimiter and functions which we will do in next article.

 

 

 

%d bloggers like this: